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;开发者_StackOverflow社区 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:
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.
I think you need to use document.write instead.
精彩评论