Greasemonkey: 如何在另一个 Greasemonkey 用户脚本中调用函数?

创建于 2016-10-28  ·  8评论  ·  资料来源: greasemonkey/greasemonkey

你好呀,

我是 Greasemonkey 的新手。
有没有办法在另一个 Greasemonkey 用户脚本中调用函数?

谢谢。

所有8条评论

不,除非另一个脚本努力通过某种方式公开 API。

没有内部方法可以做到这一点,但有一个解决方法。

具有公开功能的脚本:

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

调用函数的脚本

hello();

这就是它的要点。

当然这也意味着它可以从网站调用,而不仅仅是其他用户脚本

真的。 给它一个密码参数。

它必须是相同的选项卡。

// ==UserScript==
// <strong i="5">@name</strong>        Test call 1
// <strong i="6">@namespace</strong>   https://github.com/tiansh/
// <strong i="7">@include</strong>     http://example.com/
// <strong i="8">@version</strong>     1
// <strong i="9">@grant</strong>       unsafeWindow
// ==/UserScript==

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

setTimeout(function () {

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

}, 0);

由于沙盒保护,网站页面中的@the8472脚本无法调用您的函数。

@tiansh ,在此示例中, <strong i="6">@grant</strong> unsafeWindow禁用了沙盒保护。

@pyhedgehog你试过了吗? 与 GM 2 / 3?

此页面是否有帮助?
0 / 5 - 0 等级