Can I prevent an alert() with a Google Chrome Extension

As @MrGlass said, currently, Chrome Extensions run in a separate environment, limiting access to the actual window object and providing a duplicate that is only valid for the extension.

To solve this, we can inject a script element directly into the document. This way, you access the document’s environment and the real window object.

First, lets create the function (I added the “confirm” as well, because some confirms were annoying me so much):

var disablerFunction = function () {

    window.alert = function alert(msg) { console.log('Hidden Alert ' + msg); };
    window.confirm = function confirm(msg) { 
        console.log("Hidden Confirm " + msg); 
        return true; /*simulates user clicking yes*/ 
    };

};

Now, what we’re going to do is to transform that function in a text script and enclose it in parentheses (to avoid possible conflicts with actual vars in the page environment):

var disablerCode = "(" + disablerFunction.toString() + ")();";

And finally, we inject a script element, and immediately remove it:

var disablerScriptElement = document.createElement('script');
disablerScriptElement.textContent = disablerCode;

document.documentElement.appendChild(disablerScriptElement);
disablerScriptElement.parentNode.removeChild(disablerScriptElement);

Leave a Comment