Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hooking document.write function

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?

like image 735
Discombobulous Avatar asked Jun 21 '26 22:06

Discombobulous


1 Answers

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.

like image 103
Joseph Silber Avatar answered Jun 24 '26 13:06

Joseph Silber