How do I change the Javascript src file on client side? - javascript

Within my body tag, I have this:
<script src="http://maps.google.com/maps?file=api&v=2.x&key=ABQIAAkh87y8Hjhg76ty" type="text/javascript"></script>
Is it possible to add JavaScript or jQuery in the head of the page to change the "key" parameter in the script source. I am trying to do this before the render reaches the above tag.

It is not possible to change the src attribute before the render reaches the tag, because modern browsers will download and parse the script as soon as it reaches a script tag (in that particular format).
You can use the defer attribute to hold off execution of the script until after the DOM has completely loaded, but this attribute is only supported in IE 4+ and Firefox 3.5+.

why not dynamically create the script tag triggered by onload.
In onload: make the JQuery call, create the src url from the result, append the script tag.

I don't know that you could change the key parameter before that script is rendered but you could dynamically write the entire script tag like this:
var script = document.createElement('script');
script.setAttribute('src', 'http://maps.google.com/maps?file=api&v=2.x&key='
+ param_ssKey + '/');
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);

Related

How to get text inside script tag html?

I tried to get this link 'video_versions' text from this url https://www.instagram.com/p/Cahc9hbr9Jp/ but it doesn't show anything.
Here's my code
var c = document.createElement("html");
c.innerHTML = content;
scripts = c.querySelectorAll('script');
script = scripts[scripts.length-2];
console.log(script.innerHTML.split('video_versions').pop());
Although scriptElement.textContent is perhaps more appropriate than scriptElement.innerHTML both seem to work if they work at all.
However they only retrieve text between the opening and closing <script> tags present in the HTML source, so they are only good for reading the content of inline scripts. The URL posted doesn't strike me as the kind of page with hand-crafted inline scripts.
If you want to read the script text fetched by a script tag with a src attribute specifying its URL, you would need to repeat the fetch process in JavaScript using either the Fetch or XMLHttpRequest API for the same URL. The success of doing so depends on the server's cross origin policy allowing it.
This is because you aren't getting the innerHTML property of the script element object, you are simply returning the object of the element from the DOM.
try:
script = scripts[scripts.length-2].innerHTML;

Force browser to reload javascript files

I tried like this
<script type="text/javascript" src="myfile.js"?+Date.now()></script>
In browser it is showing as it is.
I want to add some timestamp to each js files.
i.e.,
<script type="text/javascript" src="myfile.js"?+5671836294></script>
Thanks in advance.
You can't randomly stick JavaScript anywhere you like in HTML.
When you are in the middle of an HTML start tag you can either:
End the tag with >
Write an attribute
JavaScript does not belong there.
If you want to generate an HTML attribute value dynamically when the element is created, then you must create the entire element with JavaScript.
e.g.
<script>
var s = document.createElement("script");
s.src = "myfile.js"?+Date.now();
document.head.appendChild(s);
</script>
… but you'd probably be better of solving this problem by properly configuring your HTTP headers for the script instead.
Refresh the page or rewrite the script tag and append it to the bottom of the body.
But once a page is loaded, it is loaded. You have to redeclare to overwrite.

Appending inline javascript to a script tag [duplicate]

I want to append a script tag which executes one line of JavaScript to the head of a document, rather than appending a script tag which is empty and uses the src attribute.
Here's what I've got so far:
<script type="text/javascript">
var scriptContents = 'alert("hi")';
var theScript = document.createElement('script');
theScript.type = 'text/javascript';
theScript.appendChild(scriptContents);
document.getElementsByTagName('head')[0].appendChild(theScript);
</script>
It's the appendChild(scriptContents) part that I'm having trouble with. How do I change this to get the alert to appear in the browser?
You need to append it as a text node. Try this:
theScript.appendChild(document.createTextNode(scriptContents));
You can't do
theScript.appendChild(scriptContents);
as appendChild() only appends nodes, it can't append text. You need to make a text node with:
var scriptContents=document.createTextNode('alert("hi");')
However, as Jake mentioned above, you probably just want to do:
eval('alert("hi")');

Dynamically adding a script tag to loaded HTML - error in IE7&8

I've been stuck on this for quite a while - any help would be really appreciated.
Basically I'm loading HTML into a page, but the loaded HTML needs to contain an external script in specific position within it. I found the best way to do this was using the following code:
$('#blah').load('blah.htm',
function(){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "[external script url + query string here]";
$('#blah_blah')[0].appendChild(script);
});
Edit:
The reasons I'm using "appendChild" instead of jQuery's "append" is that $.append adds the videoplayer created by the script to completely the wrong element. If I use appendChild, it is added to the correct element specified. I think this maybe to do with jQuery's insertion methods, as outlined within this answer:
Can't append <script> element
The code I'm using works great in Firefox and Chrome, but in IE7 & 8 I get the error message "Unable to get value of the property 'appendChild': object is null or undefined", and the script tag cannot be seen in the DOM.
If I include the line:
$("#blah_blah")[0].appendChild(document.createTextNode("test"));
the text node "test" is added to the DOM, and can be seen on the page - so it seems "appendChild" does work, but there is an issue with appending a script tag.
Could it possibly be an IE specific security issue?
What's wrong with:
$.getScript("script.js");

Why can't I add a string containing a script tag to innerHTML in IE

I'm trying to do the following (I'm using the prototype library):
var div = document.createElement('div');
div.innerHTML = '<script src="somescript.js"></script>';
$('banner').insert(div);
In IE, div.innerHTML property is always equal to "" after I set the property in the second line.
This snippet is inside a function which is overriding document.write() in an external vendor script, so that is why I am doing it this way rather than creating a script element and appending it to the div element directly.
Any help would really be appreciated, this is giving me grey hairs!
This one had me stymied for a bit as well. It turns out that IE does not allow the insertion of JS directly via innerHTML unless you include the 'defer' property (see the second link below). This property is unique to IE and apparently allows IE to defer execution of any JS until after the other markup has been loaded. A warning, though...if you include two script tags (as I did), there is no guarantee which one will execute first, as the scripts appear to be loaded asynchronously. This should only be a problem if your scripts are dependent on one another (as mine were).
There is an additional caveat as well...you must insert non-script markup at the same time that you insert the script. I was unable to insert the script tags by themselves, with or without the 'defer' property. Finally, the script tags must be placed after all other non-script markup being inserted. Otherwise, the script tags are stripped out of the inserted HTML.
Here are a few references:
MS innerHTML Reference:
http://msdn.microsoft.com/en-us/library/ms533897%28v=vs.85%29.aspx
MS Defer Property Reference:
http://msdn.microsoft.com/en-us/library/ms533719%28v=vs.85%29.aspx
Example of Script Insert via code (yes, it actually does work):
http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/insertScript_2.htm
My Test Code:
// I downloaded the MS example file above and tweaked their script a bit,
// resulting in this. Using the proper approach to the defer property
// (namely: defer="defer") did not provide me with consistent results, so
// sticking with 'DEFER' may be necessary.
// Note: Try moving the 'sHTML' variable to the end of the script string.
function insertScript2()
{
var sHTML="<input type=button onclick=" + "go2()" + " value='Click Me'><BR>";
var sScript = sHTML + "<SCRIPT DEFER type='text/javascript'> function go2(){ alert('Hello from inserted script.') } </SCRIPT" + ">";
ScriptDiv.innerHTML = sScript;
}
Your script tag is probably managing to be interpreted independently. Try:
div.innerHTML = '<scr' + 'ipt src="somescript.js"></scr' + 'ipt>';
You could try to do something like this instead:
function loadScript(src) {
var script = document.createElement("script");
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);
script.src = src;
}
or do
..
div.innerHTML = "<script src=\"somescript.js\"></script>";
..
you need to use escape char for the </script>
div.innerHTML = '<script src="somescript.js"><\/script>';
see why escaping / in javascript '<\/script>'?
Have you tried to add inline JS instead of loading a .js file? I've done this in the past and it worked fine for me. Not sure if that would still work with the lastest browsers / security missery.
HTH.

Categories