如何在IE 8上向页面注入javascript? [英] How do I inject javascript to a page on IE 8?

查看:132
本文介绍了如何在IE 8上向页面注入javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我有以下标记:

Lets suppose that I have the following markup:

<div id="placeHolder"></div>

我有一个JavaScript变量 jsVar 那个包含一些标记和一些JavaScript。

and I have a JavaScript variable jsVar that contains some markup and some JavaScript.

通过使用Mootools 1.1,我可以将JavaScript内容注入占位符,如下所示:

By using Mootools 1.1 I can inject the JavaScript content into the placeholder like this:

$('placeHolder').setHTML(jsVar);

这适用于Firefox,Opera甚至Safari,结果标记如下:

This works in Firefox, Opera, and even Safari and the resulting markup looks like this:

<div id="placeHolder">
    <strong>I was injected</strong>
    <script type="text/javascript">
        alert("I was injected too!");
    </script>
</div>

然而,在IE 8上我得到以下内容:

However, on IE 8 I get the following:

<div id="placeHolder">
    <strong>I was injected</strong>
</div>

有没有办法在IE 8上注入JavaScript或安全模型是否禁止我执行此操作完全没有?

Is there any way to inject the JavaScript on IE 8 or does it security model forbid me from doing this at all?

我试过Luca Matteis建议使用

I tried Luca Matteis' suggestion of using

document.getElementById("placeHolder").innerHTML = jsVar;

而不是MooTools代码,我得到相同的结果。这不是MooTools问题。

instead of the MooTools code and I get the same result. This is not a MooTools issue.

推荐答案

MSDN帖子专门解决了如何使用innerHTML将javascript插入页面。你是对的:IE确实认为这是一个安全问题,所以要求你跳过某些环节来注入脚本...大概黑客可以读取这个MSDN帖子我们可以,所以我不知道为什么MS认为这个额外的间接层安全,但我离题了。

This MSDN post specifically addresses how to use innerHTML to insert javascript into a page. You are right: IE does consider this a security issue, so requires you to jump through certain hoops to get the script injected... presumably hackers can read this MSDN post as well as we can, so I'm at a loss as to why MS considers this extra layer of indirection "secure", but I digress.

来自MSDN文章:

<HTML>
<SCRIPT>
function insertScript(){
    var sHTML="<input type=button onclick=" + "go2()" + " value='Click Me'><BR>";
    var sScript="<SCRIPT DEFER>";
    sScript = sScript + "function go2(){ alert('Hello from inserted script.') }";
    sScript = sScript + "</SCRIPT" + ">";
    ScriptDiv.innerHTML = sHTML + sScript;
}    
</SCRIPT>
<BODY onload="insertScript();">
    <DIV ID="ScriptDiv"></DIV>
</BODY>
</HTML>

如果可能,您可能希望考虑使用 document.write 注入脚本加载标记以提高安全性并减少跨浏览器的不兼容性。我知道这可能是不可能的,但值得考虑。

If at all possible, you may wish to consider using a document.write injected script loading tag to increase security and reduce cross-browser incompatibility. I understand this may not be possible, but it's worth considering.

这篇关于如何在IE 8上向页面注入javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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