Append javascript to HTML fields using through javascript - javascript

I'm currently trying to create a form dynamically through javascript after looking at this post. Everything is going smoothly until when I attempt to insert javascript to the input form's value field. I am thinking of something like this
<input type = 'hidden' name = 'q' value = '<script>...some_script...</script>'
Here is my attempt at achieving what I want above
my_form = document.createElement('form');
my_form.name = 'form_A';
....
my_tb = document.createElement('input');
my_tb.type = 'hidden';
my_tb.name = 'q';
my_tb.id = 'query';
my_tb.value = '<script>alert(document.cookie)</script>';
my_form.appendChild(my_tb);
document.body.appendChild(my_form);
document.form_A.submit();
The problem is that something is wrong (or maybe even illegal) with the line my_tb.value = '<script>alert(document.cookie)</script>'; When I run the file in my browser, it prints out all the javascript in the browser after that line, and in the developer console it says Uncaught SyntaxError: Unexpected token ILLEGAL
Is there a way to achieve what I want above while still using javascript to create form_A ? The main reason is what I was hoping I can store the value of document.cookie in a variable in javascript and use it later.
Any help would be appreciated.

Here is an example.
Create index.html file and paste the below.
<html>
<head>
<title></title>
</head>
<body>
<script>
// your site sets a cookie
document.cookie="username=John Doe";
my_form = document.createElement('form');
my_tb = document.createElement('input');
my_tb.value = document.cookie;
my_form.appendChild(my_tb);
document.body.appendChild(my_form);
alert(my_tb.value);
</script>
</body>
</html>
Run a server python -m SimpleHTTPServer
Open http://localhost:8000/

Related

How to print javascript variables and show them in console?

I'm trying to implement google ads conversion on my website and as per the google team, I added the tags they gave yet the conversion is not showing up properly.
After getting in touch with one of the team members, he told me to correct the code:
So far My code:
I m passing an email value through the URL to the 'Thank-you' page.
I m echoing the value inside a hidden input tag and calling it back using ID in javascript
I can get the value from the input and print it in the console.
<input type="hidden" id="email_for_ads" value="some#email.com">
<script>
var email_for_ads = $("#email_for_ads").val();
var enhanced_conversion_data = {
"email": email_for_ads
};
console.log(email_for_ads);
</script>
I can see the email id in the console, and I'm sure the value is being fetched.
But he said it should be like below upon inspect :
<input type="hidden" id="email_for_ads" value="some#email.com">
<script>
var email_for_ads = $("#email_for_ads").val();
var enhanced_conversion_data = {
"email": "some#email.com"
};
console.log("some#email.com");
</script>
I even tried the below code too
var baseUrl = (window.location).href; // You can also use document.URL
var email_for_ads = baseUrl.substring(baseUrl.lastIndexOf('=') + 1);
//var email_for_ads = $("#email_for_ads").val();
var enhanced_conversion_data = {
"email": email_for_ads
};
console.log(email_for_ads);
yet the same output. I can see the value in the console but on inspect. But he insists that it is that way and could be able to see the email value directly in inspecting itself.
Can someone understand, whether this is possible, if so, how can i do it.
It's possible, but very very weird, and I'd highly recommend against it - it doesn't provide any benefits except, I guess, when debugging, but when debugging it'd be easier to just retrieve the input value.
If you wanted the input value to be printed directly in the <script> tag, you'd have to create the script tag dynamically, either with document.createElement('script') or document.write.
For that to be possible, you'd need another script tag to create the dynamic script tag.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="email_for_ads" value="some#email.com">
<script>
// remove this script tag
document.currentScript.remove();
// append new script tag, with the input value directly in the source code
const email_for_ads_first = $("#email_for_ads").val();
document.write(`
<script>
var email_for_ads = $("#email_for_ads").val();
var enhanced_conversion_data = {
"email": "${email_for_ads_first}"
};
console.log("${email_for_ads_first}");
// log this script tag contents, so you can see what's in it:
console.log(document.currentScript.textContent);
<\/script>
`);
</script>
There's no good reason do this. Please don't.
You may need a server-side rendering technology to generate your email value into your HTML and scripts.
You can consider starting a service in nodejs, get the email value in the request,and in the responseļ¼Œreturn the email with your html and scripts.

Processing lines and filling fields

I read and search and study, but can't seem to write any JS out of my own head - this should be really simple but it will not work. I keep getting an error about an undefined variable "madlib7.html:411 Uncaught ReferenceError: populatefields is not defined at HTMLButtonElement.onclick"
I start with some urls that I paste into a textarea, then I click a button and first it splits the text into individual lines and stores them in variables. Next, I want to split each line by spaces and populate fields in an HTML form with select words from the resulting array via the use of innerhtml.
I know there is some way of looping through the processes, but I have not figured out how to do that yet so for now I am writing it all out the long way. I have not been able to figure out how to address the error message 'ReferenceError' from above.
Thanks for any and all help
Paul
populatefields(day1, location1, streamid1) {
document.getElementById('PanLinks').value.split('\n');
var streamInfoLine1 = resultArr[0];
var streamInfoLine2 = resultArr[1];
var streamInfoLine3 = resultArr[2];
var streamInfoLine1 = resultArr[3];
var streamInfoLine2 = resultArr[4];
var streamInfoLine3 = resultArr[5];
var streamInfoLine1 = resultArr[6];
var streamInfoLine2 = resultArr[7];
var streamInfoLine3 = resultArr[8];
streamInfoLine1.split(' ');
var day1 = resultArr[0];
var location1 = resultArr[3];
var streamID1 = resultArr[4];
document.getElementById("location1").innerHTML= location1;
document.getElementById("time1").innerHTML= day1;
document.getElementById("streamid1").innerHTML= streamID1;
}
could you use stackoverflow built in code sandbox to include all your code in html, javascript code? it seems like the issue is on your html file madlib7.html, where your onclick listener isn't defined on the button. nor did I see anything from your code that indicates any event listener has been setup to perform that button task. so it's hard to help debug what exactly it is.

queryselector does work in console but doesn't work in .js file

I wanted to add a paragraph element in a html file, and i succeeded. But, I just wanted to try in another way.
And i found a way which add the p element in a page.
This code is from stackoverflow.
<script type="text/javascript">
window.onload = function() {
var para = document.createElement('p');
para.innerHTML = '';
document.body.appendChild(para);
};
</script>
By using this internal script, successfully added p element.
And i added external script with defer attribute, and inside that, entered these code.
const para = document.querySelector('p');
para.textContent = 'hi';
but it doesn't work. in debugging tool, it says "Cannot set property 'textContent' of null".
So, I checked in console,
const check = document.body.querySelector('p');
check.textContent = 'hi';
it does work very well..
I just thought
when I load my HTML,
1st : load internal js file - make <p>. 2nd : parse whole HTML codes.
3rd : load external js file - manipulate <p>. and it will work well.
So, these are my questions.
Why 'para' constant doesn't be made in .js file?
what is the difference with console running and source file running in this case?
If you are using multiple external resources to generate markup. Try this:
const element = window.parent.document.querySelector(selector);

Javascript editors and console.log

I used several editors for javaScript and i write
var firstName = "John";
console.log(firstName);
problem is that i do not get console.log in Chrome (or other browser)
anyone knows what might happening?
Simply writing:
var firstName = "John"; console.log(firstName);
Isn't enough for javascript to run. Javascript is a scripting language meaning you need to provide some other infrastructure for it to work. In this case that infrastructure is HTML. You can use HTML and Javascript together like so:
<!DOCTYPE html>
<html>
<script>
var firstName = "John"; console.log(firstName);
</script>
</html>
The script tags indicate that you are writing Javascript. Save this file as a .html file and then right-click your file and click view in chrome. Then check the console for results
Check:
You have saved the file (something like index.html)
You have the correct file open in the browser
You have put the js inside a script tag

How to make a JQuery routine write to a text file on a computer desktop?

I want to make a JQuery routine that can write information (append) to a text file that either exists or does not exists. If the file does not exists than it should create the file and if it does it should either append or start writing new data to the file. I think append would be the best choice for a file logger. So it must append the data to the file.
I found this code on the internet and am trying to work it around so that I can use it on my page to write information to a simple text file.
Question: How can I make the following code log to a file for download?
Below is the new code and how I read the page that was listed in the comments on how a logger in Java script should work. The code is not working and I am not really certain as to why.
I am not really certain as to how the download works either but if I can just get the logger to work I will be happy for the time being.
Code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
<script src="log4moz.js">
</head>
<script>
getLocalDirectory : function() {
let directoryService = Cc["#mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties);
// this is a reference to the profile dir (ProfD) now.
let localDir = directoryService.get("ProfD", Ci.nsIFile);
localDir.append("XULSchool");
if (!localDir.exists() || !localDir.isDirectory()) {
// read and write permissions to owner and group, read-only for others.
localDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0774);
}
return localDir;
}
let myFile = XULSchool.getLocalDirectory();
myFile.append("someFile.txt");
let formatter = new Log4Moz.BasicFormatter();
let root = Log4Moz.repository.rootLogger;
let logFile = this.getLocalDirectory(); // remember this?
let appender;
logFile.append("log.txt");
root.level = Log4Moz.Level["All"];
appender = new Log4Moz.RotatingFileAppender(logFile, formatter);
appender.level = Log4Moz.Level["All"];
root.addAppender(appender);
this._logger = Log4Moz.repository.getLogger("XULSchool.SomeObject");
this._logger.level = Log4Moz.Level["All"];
this._logger.fatal("This is a fatal message.");
this._logger.error("This is an error message.");
this._logger.warn("This is a warning message.");
this._logger.info("This is an info message.");
this._logger.config("This is a config message.");
this._logger.debug("This is a debug message.");
this._logger.trace("This is a trace message.");
</script>
<body>
<form id="addnew">
<input type="text" class="A">
<input type="text" class="B">
<input type="submit" value="Add">
</form>
</body>
</html>
#Smeegs says this nicely
Imagine a world where any website can edit files on your computer
JavaScript (or jQuery) cannot touch the user's file system.
Even if you find some hacked up thing that works via ActiveXObject, you should not attempt to do this. Cross-browser support would be very narrow for this feature.
If you want to write out file, just provide the user with a download.
If this is just a means of reading/writing some kind of data, look into localstorage.

Categories

Resources