7

如果我在任何页面上的 Firebug 中运行以下行:

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

为什么alert命令没有执行?

4

4 回答 4

6

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>.

于 2012-07-27T20:26:38.320 回答
0

实际上您可以使用eval,但这不是解决安全问题的好习惯。你可以这样做:

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

希望能帮助到你!

于 2012-07-27T20:17:01.507 回答
0

最好使用创建元素并附加它们,而不是使用 innerhtml 直接插入任何 html。

你可以在这里阅读更多关于它的信息:https ://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet

此片段有效:

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

这是实际示例: https ://jsfiddle.net/BrianLayman/4nu667c9/

于 2016-06-16T16:27:36.533 回答
-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");

于 2012-07-27T20:23:51.197 回答