How to override the alert function with a userscript?

Update: For modern versions of Tampermonkey, Violentmonkey, Greasemonkey (but strongly recommended to avoid GM 4+):
You can intercept alert() in most cases by using @run-at document-start. For example, load this script and then visit the test page:

// ==UserScript==
// @name    _Overwrite Alert
// @match   *://output.jsbin.com/*
// @grant   none
// @run-at  document-start
// ==/UserScript==

var alrtScope;
if (typeof unsafeWindow === "undefined") {
    alrtScope = window;
} else {
    alrtScope = unsafeWindow;
}

alrtScope.alert = function (str) {
    console.log ("Greasemonkey intercepted alert: ", str);
};

Note that if you are running Tampermonkey, you can block alerts more effectively by switching to Inject Mode: Instant:
Tampermonkey Settings => Config mode: Advanced => Experimental => Inject Mode: Instant.


If your script requires GM_ functions, it must set @grant other than none. In that case use exportFunction() like so:

// ==UserScript==
// @name            _Overwrite Alert
// @match           *://output.jsbin.com/*
// @grant           GM_addStyle
// @run-at          document-start
// ==/UserScript==

function myAlert (str) {
    console.log ("Greasemonkey intercepted alert: ", str);
}
unsafeWindow.alert   = exportFunction (myAlert, unsafeWindow);


Old answer, for Greasemonkey before August 2011:

unsafeWindow.alert=function() {}; works fine in select situations.

But, if that really is the code on the page, then you will not be able to stop that alert using Greasemonkey.

This is because that alert will fire during the page load and before the DOMContentLoaded event — which is when Greasemonkey is fired.

Load this GM script:

// ==UserScript==
// @name            Overwrite Alert
// @description     Overwrites alert()
// @include         http://jsbin.com/*
// ==/UserScript==

unsafeWindow.alert=function() {};

Then visit: http://jsbin.com/ajeqe4/6 .

Inspecting the code (http://jsbin.com/ajeqe4/6/edit), You will see 3 alerts.   Greasemonkey is only able to stop the alerts that fire on load (usually).

Other factors can block GM’s ability to stop the alert… The page loads too fast or closures, perhaps.


Paste the source of that page, unedited if at all possible, at pastebin.com. There may be something else you can do.   Maybe block the script via adblock?

Otherwise, you’ll have to write an extension/add-on.

Leave a Comment