Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
126
rated 0 times [  132] [ 6]  / answers: 1 / hits: 32830  / 14 Years ago, wed, september 1, 2010, 12:00:00

I want to dynamically add javascript to an existing script element something like:



var se = document.createElement('script');
se.setAttribute('type', 'text/javascript');
se.innerHTML = 'alert(1)';
document.getElementsByTagName('head').item(0).appendChild(se);


The interesting part is se.innerHTML = 'alert(1)'; and if it is valid? If not how can I do this the right way?


More From » html

 Answers
6

That's not adding JavaScript to an existing script element, it's creating a new script element and adding it to the document.



This does work in modern browsers, but you wouldn't normally do it unless you had some code in a variable that you really needed to execute in global context (so you couldn't use new Function(), or eval from inside a function).



What's the use case? Do you really have to do this?



If you did try to change the script's content by writing to the text content of a <script> that was already in the document, it would not cause the new script content to be run, it would just change the contents of the DOM. The exact circumstances of what causes new script to be run when a <script> element is manipulated vary from browser to browser (though HTML5 is trying to standardise it); for now it is better to avoid doing anything other than simply creating and appending a new script. (And even better to avoid scripting <script> at all, if possible.)



Setting innerHTML will work; RoToRa's method with createTextNode is better though. For <script> in an old-school-HTML document, innerHTML will actually do the same thing as createTextNode, since <script> is a CDATA element which cannot contain markup. It would matter for XHTML-served-as-XML though, and in general it is cleaner to avoid innerHTML and its escaping problems when you just want to set plain text.



Also, you can use [0] instead of item(0) (this is defined as part of the JavaScript DOM bindings), and you should in general avoid getAttribute/setAttribute; use the DOM HTML properties like se.type=... instead, which are more readable and less buggy in IE (though the IE bugs wouldn't affect you for the type attribute).


[#95737] Sunday, August 29, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elishaannac

Total Points: 28
Total Questions: 97
Total Answers: 101

Location: Samoa
Member since Mon, Nov 8, 2021
3 Years ago
elishaannac questions
Sun, Dec 5, 21, 00:00, 3 Years ago
Mon, Jun 14, 21, 00:00, 3 Years ago
Mon, Jul 22, 19, 00:00, 5 Years ago
Mon, Jul 8, 19, 00:00, 5 Years ago
;