setting innerHTML with a script inside

六眼飞鱼酱① 提交于 2019-12-24 15:03:27

问题


If I run the following line in Firebug on any page:

document.documentElement.innerHTML="<script>alert(1)</script>";

why isn't the alert command executed?


回答1:


It looks like that your <script> tag is being added as you expect, but the code within it is not being executed. The same failure happens if you try using document.head (or any other DOM element, it seems). For whatever reason (possibly standards compliance, possible security), inline code inside of <script> blocks that are added via .innerHTML simply doesn't run.

However, I do have working code that produces similar functionality:

var script = document.createElement('script');
script[(script.innerText===undefined?"textContent":"innerText")] = 'alert(1);';
document.documentElement.appendChild(script);

Here, you add the <script> block with documentElement.appendChild and use textContent or innerText to set the content of the <script>.




回答2:


Actually you can use eval but that's not a good practice for security issues. You can do something like this:

var scr = document.createElement('script');
scr.src = 'yourscriptsource';
document.body.appendChild(scr);

Hope it helps!




回答3:


It is always best to use create the elements and append them rather than straight inserting any html using innerhtml.

You can use read more about it here: https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet

This fragment works:

var newScript = document.createElement( "script" );
newScript.type = 'text/javascript';
var scriptContent = document.createTextNode( "googletag.cmd.push( function() { googletag.display( '" + encodeURIComponent( divID ) + "' ); } );" ); 
newScript.appendChild( scriptContent ); 

Here is the example in action: https://jsfiddle.net/BrianLayman/4nu667c9/




回答4:


You don't to do that. In Firebug go to the "Console" tab. You can enter code directly there. Next to the three blue angle brackets at the bottom of the console type this and then hit the enter key: alert("asdf");



来源:https://stackoverflow.com/questions/31287119/script-inserted-with-innerhtml-not-executing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!