1

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

2 Answers 2

3

After analyzing what jQuery does, I saw that they prepend a little dummy text and removes it again:

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.

Sign up to request clarification or add additional context in comments.

Comments

0

I think you need to use document.write instead.

1 Comment

Can't do that, as it clears the page when executed after the page has been rendered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.