Greasemonkey: How to call a function in another Greasemonkey userscript?

Created on 28 Oct 2016  ·  8Comments  ·  Source: greasemonkey/greasemonkey

Hi there,

I am new to Greasemonkey.
Is there any way to call a function in another Greasemonkey userscript?

Thanks.

All 8 comments

no, not unless the other script makes some effort to expose APIs through some means.

There's no internal method to do it, but there's a work around.

Script with exposed function:

unsafeWindow.hello = hello;
function hello() {alert("hello world");}

Script to call the function

hello();

That's the jist of it.

of course that also means it can be called from the website, not just other userscripts

True. Give it a password parameter.

It has to be same tab.

// ==UserScript==
// @name        Test call 1
// @namespace   https://github.com/tiansh/
// @include     http://example.com/
// @version     1
// @grant       unsafeWindow
// ==/UserScript==

unsafeWindow.x = function (str, callback) {
  console.log('%o.x: %o', this, arguments);
  alert('x says: ' + str);
  callback(str + 'from x');
};
// ==UserScript==
// @name        Test call 2
// @namespace   https://github.com/tiansh/
// @include     http://example.com/
// @version     1
// @grant       unsafeWindow
// ==/UserScript==

setTimeout(function () {

unsafeWindow.x('hello', function (nstr) {
  console.log('%o.y: %o', this, arguments);
  alert('y says: ' + nstr);
});

}, 0);

@the8472 scripts in page from website cannot call your function due to sandbox protection.

@tiansh, in this example sandbox protection was disabled by @grant unsafeWindow.

@pyhedgehog Had you tried? With GM 2 / 3?

Was this page helpful?
0 / 5 - 0 ratings