用里面的脚本设置innerHTML [英] setting innerHTML with a script inside

查看:122
本文介绍了用里面的脚本设置innerHTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

为什么不执行 alert 命令?

推荐答案

看起来你的< script> 标签 is 按预期添加,但其中的代码未被执行。如果您尝试使用 document.head (或任何其他DOM元素,似乎)会发生同样的故障。无论出于何种原因(可能符合标准,可能的安全性),通过 .innerHTML < script> 块内的内联代码$ c>根本不运行。

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);

在这里,您添加< script> 阻止 documentElement.appendChild 并使用 textContent innerText 设置< script> 的内容。

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

这篇关于用里面的脚本设置innerHTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆