3

I'm working on a Chrome extension that requires me to intercept the document.write function (Note: I am using content script). I'm using the method here: http://sitr.us/2012/09/04/monkey-patching-document-write.html But it's not working correctly. This is what I have right now:

(function() {
    var originalWrite = document.write;
    alert("checkpoint 1");
    document.write = function() {
        alert("checkpoint 2");

        //secret stuff here         

        return Function.prototype.apply.call(
                        originalWrite, document, arguments);    
    }
})();

However, the "checkpoint 2" alert inside my hook never gets called when I call document.write on a web page. What am I doing wrong?

Discombobulous
  • 1,112
  • 2
  • 14
  • 25

1 Answers1

4

Your extension runs in its own sandbox, and has no access to the web page's JavaScript environment. Overwriting document.write in your extension does not affect the document.write function of the web page itself.

Here's a quote from the docs:

However, content scripts have some limitations. They cannot:

  • Use chrome.* APIs (except for parts of chrome.extension)
  • Use variables or functions defined by their extension's pages
  • Use variables or functions defined by web pages or by other content scripts

To alter the document.write function of the webpage, you'll have to insert your script into the DOM.

Community
  • 1
  • 1
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
  • I'm using content script... so my script is inserted into the DOM – Discombobulous Jan 23 '13 at 02:49
  • @EricChen - Wrong. Content scripts [are *not* inserted into the DOM](http://stackoverflow.com/questions/10285886/chrome-extension-adding-external-javascript-to-current-pages-html#answer-10371025). – Joseph Silber Jan 23 '13 at 02:50