Can I create a Google chrome extension to prevent the page from doing an alert()
?
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.
You can set up Chrome to get notifications, such as meeting reminders, from websites, apps and extensions.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With