简体   繁体   中英

Can you run javascript that is written into the DOM (inner HTML)?

For instance:

document.getElementById("test").innerHTML= "<script>document.write('worked')</script>";

The result is:

<div id="test"><script>document.write('worked')</script></div>

ie no JS is run. Why don't I just make .innerhtml "worked" to start with? This is a question of technical ability. Is it possible to run javascript in the DOM with the given scenario?

Thank you

It's not enough to simply set the innerHTML to something that contains a script tag. You must create a script element and append it to the DOM. I believe the intent is to give some cross site scripting protection when injecting massive blobs of content.

var script = document.createElement('script');
script.innerHTML = "alert('ran some JS');";
document.body.appendChild(script);

Example: http://jsfiddle.net/axvaT/

document.write won't work like you think though. document.write will not place text where the script tag is. Instead it will place text where the HTML parser is currently looking at. Depending on when the JS code is run, these may be the same, or maybe entirely different.

So for this reason, among others, never use document.write for anything. Ever. Even debugging.


Lastly, while sometimes it's useful to inject a script tag pointing to some other js file:

var script = document.createElement('script');
script.src = 'somefile.js';
document.head.appendChild(script);

Doing this with a script tag that has JS in it makes no sense. You are using javascript to create a script tag that should immediately run some javascript. Why not just run that javascript that you want to run away instead of creating a new script tag to do it for you?

So don't do:

var script = document.createElement('script');
script.innerHTML = "alert('ran some JS');";
document.body.appendChild(script);

Instead just do:

alert('ran some JS');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM