Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

html - Can I add javascript dynamically to an existing script element

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

All browsers currently support a javascript text property, and will evaluate the text when a new script element (without a src attribute) is added to the document.

innerHTML or adding child nodes to a script element do not evaluate the script in all browsers.

function addCode(code){
    var JS= document.createElement('script');
    JS.text= code;
    document.body.appendChild(JS);
}

//test case

var s= 'document.body.ondblclick=function(e){
'+
'e=window.event? event.srcElement:e.target;
'+
'alert(e.id || e.tagName);
'+
'}
alert("ready to double click!");';

addCode(s);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...