2

In Greasemonkey I can rewrite the global alert() function with:

window.alert = function() {...}

and it works anywhere.
But, in Tampermonkey (Chrome), it only works on it's own script.

Why? And could I make it work globally?

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
zsytssk
  • 702
  • 1
  • 6
  • 14

1 Answers1

3

Actually, that will only work in Greasemonkey sometimes. The grant mode has to be none -- which I recommend against. As you have discovered, accidentally tripping that mode makes un-portable scripts -- along with other sins which are beyond the scope of this question.

To make this code work on Tampermonkey (and Greasemonkey too), use unsafeWindow, like so:

// ==UserScript==
// @name     _YOUR_SCRIPT_NAME
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant    unsafeWindow
// ==/UserScript==

unsafeWindow.alert = function() {...}


Or, use script injection as shown in this answer.



The @grant unsafeWindow directive is for Greasemonkey -- to restore the sandbox and to allow use of unsafeWindow. This lets the same script work the same way in both Tampermonkey and Greasemonkey.

Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295