简体   繁体   English

IE中的Javascript HTML和脚本注入问题

[英]Javascript HTML and Script injection issue in IE

I have a javascript variable containing escaped HTML. 我有一个JavaScript变量,其中包含转义的HTML。 There can be script tags inside the HTML, like this: HTML内可以有脚本标签,如下所示:

var valueToInsert = "%3Cscript%20type%3D%22text/javascript%22%3Ealert%28%27test%27%29%3B%3C/script%3E%0A%3Cscript%20type%3D%22text/javascript%22%20src%3D%22http%3A//devserver/testinclude.js%22%3E%3C/script%3E%0A%3Cimg%20src%3D%22http%3A//www.footballpictures.net/data/media/131/manchester_united_logo.jpg%22%20/%3E"

I want to append this to the DOM, and get all the javascript fired as expected. 我想将此附加到DOM,并按预期启动所有JavaScript。 Right now I'm using this approach: 现在,我正在使用这种方法:

var div = document.createElement("div");
div.innerHTML = unescape(valueToInsert);
document.body.appendChild(div);

In IE, at the time i set div.innerHTML - all script tags are removed. 在IE中,当我设置div.innerHTML时-所有脚本标签均被删除。

If I use jQuery to and do this: 如果我使用jQuery来做到这一点:

$(document.body).append(valueToInsert)

It all works fine. 一切正常。 Bad thing is, that I cannot use jQuery as this code will be added to sites I'm not in control of using some "already-implemented" script includes. 不好的是,我不能使用jQuery,因为此代码将添加到我无法控制使用某些“已实现”脚本包括的网站中。

Does someone have a trick? 有人有把戏吗? If jQuery can do it, it must be possible? 如果jQuery可以做到,那一定有可能吗?

I had another issue in Opera. 我在Opera中遇到另一个问题。 I changed the injection script to be this: (still doesn't work in IE) 我将注入脚本更改为:(仍然无法在IE中运行)

    var div = document.createElement("div");
    div.innerHTML = unescape(valueToInsert);
    var a = new Array();

    for (var i = 0; i < div.childNodes.length; i++)
        a.push(div.childNodes[i]);

    for (var i = 0; i < a.length; i++)
    {
        if (a[i].nodeName == "SCRIPT" && a[i].getAttribute("src") != null && a[i].getAttribute("src") != "" && typeof (a[i].getAttribute("src")) != "undefined")
        {
            var scriptTag = document.createElement("script");
            scriptTag.src = a[i].getAttribute("src");
            scriptTag.type = "text/javascript";
            document.body.appendChild(scriptTag);
        }
        else if (a[i].nodeName == "SCRIPT")
        {
            eval(a[i].innerHTML);
        }
        else
        {
            document.body.appendChild(a[i]);
        }
    }

After analyzing what jQuery does, I saw that they prepend a little dummy text and removes it again: 在分析了jQuery的功能之后,我看到他们在前面添加了一个虚拟文本并再次将其删除:

var div = document.createElement("div");
div.innerHTML = "removeMe" + unescape(valueToInsert);
div.removeChild(div.childNodes[0]);
document.body.appendChild(div);

And that works perfectly in FF, IE, Chrome, Opera and Safari. 并且在FF,IE,Chrome,Opera和Safari中完美运行。

我认为您需要改用document.write。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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