Cross browser issue with script tag - javascript

I have the below code that will dynamically create the script tag.
<html>
<head>
<title>Applying</title>
</head>
<body>
<script>
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
var variable1 = getUrlVars()["parameter1"];
var myScript = document.createElement('script');
myScript.setAttribute('type', 'text/javascript');
myScript.setAttribute('urlId', '420');
myScript.setAttribute('dataTitle', variable1);
myScript.setAttribute('dataemail', 'admin#domain.net');
document.body.appendChild(myScript);
</script>
<input name="Apply" type="button" id="Apply" value="Apply" ONCLICK="window.location.href='https://www.google.com?'">
</body>
</html>
But somehow the above code doesn't work in IE but it works fine in Chrome. I am not sure what is the reason? Can anybody help me with that?
This whole things doesn't work in IE.
var myScript = document.createElement('script');
myScript.setAttribute('type', 'text/javascript');
myScript.setAttribute('urlId', '420');
myScript.setAttribute('dataTitle', variable1);
myScript.setAttribute('dataemail', 'admin#domain.net');
document.body.appendChild(myScript);

You can dynamically add a script element using the following function.
var create_script = function(data) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.text = data;
//if you have to debug dynamically loaded script in chrome use the following - sourceURL has changed in the recent versions of chrome devetools.
//script.text = data + "\n\n //# sourceURL=" + ns + ".js\n";
//append the script element to body or head or where it seems fit.
document.body.appendChild(script);
}
the "data" parameter is the actual javascript code/URL that will form the part of the script tag. You are missing this in your code.
EDIT:
for non-standard attributes you might want to change the doctype according to http://www.w3schools.com/DTD/dtd_attributes.asp

Related

Loading sequence of scripts in html

I want to load a constants file as per the language the user has selected. For that I want to load the scripts dynamically.
<html>
<body>
<script type="text/javascript">
var jsElement = document.createElement("script");
jsElement.type = "application/javascript";
jsElement.src = "../constants.en.js";
document.body.appendChild(jsElement);
</script>
<script type="text/javascript" src="../js/RandomScript.js"></script>
</body>
Whole code is in HTML.
When I tried the code above, RandomScript.js is loaded before the constant file.
How can I maintain sequence of loading files.
I am not using jQuery or something, so is there any way to do interpolation of src of script?
You can use onload event listener to load .js files sequentially.
First create an array of URLs of scripts. Then loop through it recursively. onload event listener ensures that the scripts are loaded sequentially.
var scriptURLs = [
"../constants.en.js",
"../js/RandomScript.js"
];
function loadScript(index){
if(index >= scriptURLs.length){
return false;
}
var el = document.createElement('script');
el.onload = function(){
console.log("Script loaded: ", scriptURLs[index]);
loadScript(index+1);
}
el.src = scriptURLs[index];
document.body.appendChild(el);
// OR
// document.head.appendChild(el);
}
loadScript(0); // Load the first script manually.
Hope this helps.
var jsElement = document.createElement("script");
jsElement.type = "application/javascript";
document.body.appendChild(jsElement);
jsElement.onload = () => {
callyournewScript();
}
jsElement.src = "../constants.en.js";
Load the ../js/RandomScript.js after loading the ../constants.en.js like following
<body>
<script type="text/javascript">
var jsElement = document.createElement("script");
jsElement.type = "application/javascript";
jsElement.src = "../constants.en.js";
document.body.appendChild(jsElement);
var script = document.createElement("script");
script.src = "../js/RandomScript.js";
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);
</script>
<!-- <script type="text/javascript" src="../js/RandomScript.js"></script> -->
</body>

firefox not firing $(document).ready( function() when window.open

I am trying to create a new window dynamically using window.open() and $(document).ready( function() { ... }); I got it working on Chrome and Internet Explorer but firefox is not trigering the jQuery code. See code below:
index.html code:
<html>
<head>
</head>
<body>
Link
<script type="text/javascript">
function showDetails(name, timeStamp)
{
var w = window.open("", timeStamp);
var s = w.document.createElement("script");
s.type = "text/javascript";
s.src = "var eventArray = [];";
w.document.body.appendChild(s);
var s = w.document.createElement("script");
s.type = "text/javascript";
s.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
w.document.body.appendChild(s);
var s = w.document.createElement("script");
s.type = "text/javascript";
s.src = "test.js";
w.document.body.appendChild(s);
w.document.title = name;
w.document.close();
return false;
}
</script>
</body>
test.js code:
alert("executing js file");
$(document).ready( function()
{
alert("document ready fired");
});
The first alert "executing js file" is executing but not the second one "document ready fired".
Any idea how can I make this work on firefox?
NOTE:
w.document.close(); and return false; is added following this post but still not working...
jquery is loading properly
thank you very much in advance
My inner sense says:
s.src = "jquery1.10.2.js";
should be:
s.src = "jquery-1.10.2.js";
Or any valid url that points to jquery.
Why you always use same variable names? Could you please try it like:
<script type="text/javascript">
function showDetails(name, timeStamp) {
var w = window.open("", timeStamp);
var s1 = w.document.createElement("script");
s1.type = "text/javascript";
s1.src = "var eventArray = [];";
w.document.body.appendChild(s1);
var s2 = w.document.createElement("script");
s2.type = "text/javascript";
s2.src = "jquery1.10.2.js";
w.document.body.appendChild(s2);
var s3 = w.document.createElement("script");
s3.type = "text/javascript";
s3.src = "test.js";
w.document.body.appendChild(s3);
w.document.title = name;
w.document.close();
return false;
}
</script>

How do I add dynamic javascript to the head tag from a string, not a file?

I am using Javascript to generate additional custom javascript and then adding it to the HEAD tag. The code below works great adding a javascript file, but what if the script is in a variable just generated?
var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");
scriptTag.setAttribute("src", "myfile.js");
document.getElementsByTagName("head")[0].appendChild(scriptTag);
Thank you for your attention.
// script text
var txt = "alert('foo');";
var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");
// append it in a text node
scriptTag.appendChild(document.createTextNode(txt));
document.getElementsByTagName("head")[0].appendChild(scriptTag);
FWIW, you don't need a script tag for this. You can use the Function constructor instead.
var txt = "alert('foo');";
Function(txt)();
var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");
scriptTag.innerHTML = "What you want here";///....
document.getElementsByTagName("head")[0].appendChild(scriptTag);
Live DEMO
Both answers seem ok specially the one from #gdoron.
I've written a simple example in case you want to do the same thing in jquery: http://jsfiddle.net/bitoiu/EKpGg/
Snippet:
$(function(){
var script = document.createElement( 'script' );
script.type = 'text/javascript';
// script.url = 'some valid url';
$('head').append( script );
});​

javascript - how to insert a script tag to div?

How to do that:
document.getElementById('target').innertHTML = "<script> alert(1); <script>";
<div id="target"></div>
script will be print on browser like a string.How to do is as script ?
I believe it is better to use pure DOM manipulation. Like this :
var s = document.createElement('script');
s.setAttribute('type', 'text/javascript');
s.value = 'alert(1)';
document.getElementById('target').appendChild(s);
Just don't escape your < and >s:
document.getElementById('target').innertHTML = "<script> alert(1); <\/script>";
You cannot use innerHTML for scripts anymore. It won't work and the console will not show any error. Instead you dynamically add scripts.
This is for external scripts:
var newScript = document.createElement("script");
newScript.src = "http://www.example.com/my-script.js";
target.appendChild(newScript);
And this is for inline scripts:
var newScript = document.createElement("script");
var inlineScript = document.createTextNode("alert('Hello World!');");
newScript.appendChild(inlineScript);
target.appendChild(newScript);
Credit to Daniel Crabtree
document.getElementById('target').innertHTML = '<script type="text/javascript"> alert(1); </script>';

Call Chrome.extension.sendRequest from a dynamically inserted js?

I'm currently trying to insert dynamically a JS block on a webpage using jQuery but it didn't work. I tried this :
var body = $('body');
var injectJs = $('<script type=text/javascript>' +
'$(document).click(function() {' +
'dropMenu("dropMenu1", 0);' +
'});');
body.append(injectJs);
EDIT : 16:26
I've succeed to insert the code by this way :
/* Importation de Tool.js */
var scriptImport = document.createElement('script');
scriptImport.type = 'text/javascript';
scriptImport.src= chrome.extension.getURL('js/Tool.js');
head.appendChild(scriptImport);
/* Injection du script onClick */
var script = document.createElement('script');
script.type = 'text/javascript';
script.innerHTML = "document.addEventListener('click', function(){ dropMenu('slideUp', 0); alert('TRY ME AGAIN'); });";
And dropMenu :
function dropMenu(dropMenuPage, marginLeft)
{
var msg = "";
msg = msg.concat(dropMenuPage, "|", marginLeft);
chrome.extension.sendRequest({dropMenu : msg});
alert('After send');
}
The problem is that the sendRequest is impossible from this page... Someone have an idea ?
Thanks in advance.
You need a closing </script> at the end there...
I think its just your script stag isn't closed
var b= $('body');
var injectJs = $('<script type=text/javascript> $(document).click(function() {alert("yes");});</script>');
b.append(injectJs);
Use eval function, such as eg:
var body = $('body');
var injectJs = eval("$(document).click(function() {alert('hello')})");
body.append(injectJs);
Why not use content scripts for this? Injecting script directly to the page is only required if you need to access js variables from the page. For your dropMenu() a content script should be enough.
You cannot use Chrome API inside injected js. You would need to also inject a content script, and using custom DOM events you would be able to communicate with it from your injected script. Then this content script would be able to call Chrome API and communicate with a background page. Sounds like a pain to me. I would suggest you go this route only if there is no other ways possible.
// Importation of jQuery.js
var scriptImport = document.createElement('script');
scriptImport.type = 'text/javascript';
scriptImport.src= chrome.extension.getURL('js/jquery.js');
head.appendChild(scriptImport);
// Injection of onClick script
var script = document.createElement('script');
script.type = 'text/javascript';
script.innerHTML =
"document.addEventListener('click', function()" +
"{ if(document.getElementById('dropMenu')) {" +
"$('#dropMenu').slideUp(800, function() {" +
"$(this).remove();" +
"});" +
"}});";
I've finally done this, it works :)

Categories