Javascript HTML and Script injection issue in IE

Posted by MartinHN on Stack Overflow See other posts from Stack Overflow or by MartinHN
Published on 2010-04-19T12:51:22Z Indexed on 2010/04/19 13:43 UTC
Read the original article Hit count: 322

Filed under:

Hi

I have a javascript variable containing escaped HTML. There can be script tags inside the HTML, like this:

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

If I use jQuery to and do this:

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

Does someone have a trick? If jQuery can do it, it must be possible?

I had another issue in Opera. I changed the injection script to be this: (still doesn't work in 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]);
        }
    }

© Stack Overflow or respective owner

Related posts about JavaScript