Question

If a script contains:

document.write("<iframe>ads here</iframe>");

If it's included in the html before the page is requested for load, it might look something like this:

<html>
<!-- stuff !-->
<div><script src="document_write.js" type="text/javascript"></script></div>
<body>
</html>

Loading an html page with the code similar to above will result in the <iframe> being placed in the <div> tag which housed the script. If the document.write() is called after the page load, it will overwrite the whole page.

Chrome extensions' content scripts will also overwrite a page with document.write, or crash it - depending on when in the lifecycle of a page it was called.

Is there a way to insert scripts containing document.write() in Chrome's content scripts?

Was it helpful?

Solution

I had faced the same problem when I was working with some conversion tracking scripts on my ajax site. I ended up overriding document.write, which fixed the problem.

$(document).ready(function() {
    document.write = function(str) {
        var moz = !window.opera && !/Apple/.test(navigator.vendor);
        if (str.match(/^<\//))
            return;
        if (!window.opera)
            str = str.replace(/&(?![#a-z0-9]+;)/g, "&amp;");
        str = str.replace(/<([a-z]+)(.*[^\/])>$/, "<$1$2></$1>");
        if (!moz)
            str = str.replace(/(<[a-z]+)/g, "$1 xmlns='http://www.w3.org/1999/xhtml'");
        var div = document.createElementNS("http://www.w3.org/1999/xhtml", "div");
        div.innerHTML = str;
        var pos;
        if (!moz) {
            pos = document.getElementsByTagName("*");
            pos = pos[pos.length - 1];
        } else {
            pos = document;
            while (pos.lastChild && pos.lastChild.nodeType == 1)
                pos = pos.lastChild;
        }
        var nodes = div.childNodes;
        while (nodes.length)
            pos.parentNode.appendChild(nodes[0]);
    };
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top