Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Can I create a Google chrome extension to prevent the page from doing an alert() ?

like image 867
Drew LeSueur Avatar asked Jun 03 '10 06:06

Drew LeSueur


People also ask

How can I disable JavaScript popups alerts in Chrome?

Open Chrome DevTools. Press Control+Shift+P or Command+Shift+P (Mac) to open the Command Menu. Start typing javascript , select Disable JavaScript, and then press Enter to run the command. JavaScript is now disabled.

Can a Chrome extension send a notification?

You can set up Chrome to get notifications, such as meeting reminders, from websites, apps and extensions.


1 Answers

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);
like image 199
Daniel Möller Avatar answered Oct 16 '22 12:10

Daniel Möller