首页 > 解决方案 > 在不同页面上运行的 2 个greasemonkey 脚本之间共享数据

问题描述

使用 Firefox 68 和 Greasemonkey 4.9,我想从网页上的脚本中设置一个值,并从另一个网页上的另一个脚本中获取相同的值。它似乎不起作用。我怎样才能做到这一点 ?这是我尝试过的:

脚本 1

// ==UserScript==
// @name     My EDIT
// @version  1
// @match http://one.local/stuff/edit*
// @grant       GM.setValue
// @grant       GM.getValue
// ==/UserScript==

(async () => {
  let count = await GM.getValue('count', 0);
  await GM.setValue('count', count + 1);
  console.log(count);
})();

脚本 2

// ==UserScript==
// @name     My VIEW
// @version  1
// @match http://www.two.local/view
// @grant       GM.getValue
// ==/UserScript==

(async () => {
  let count = await GM.getValue('count', 0);
  console.log(count);
})();

即使值在我多次访问http://one.local/stuff/edit时增加,我在访问 http://www.two.local/view 时也无法获得这些(它仍然是 0 !

标签: greasemonkeygreasemonkey-4

解决方案


任何好的脚本管理器都不应允许脚本 A 访问脚本 B 存储,因为这将是严重的安全漏洞。

您可以将脚本组合成一个脚本,在两个页面上运行。这样存储就可以共享了。

简单的例子:

// ==UserScript==
// @name            Combined
// @version         1
// @match           http://one.local/stuff/edit*
// @match           http://www.two.local/view
// @grant           GM.setValue
// @grant           GM.getValue
// ==/UserScript==

(async () => {

// code for one.local  
if (location.hostname === 'one.local') {  

  const count = await GM.getValue('count', 0);
  await GM.setValue('count', count + 1);
  console.log(count);
}
// code for www.two.local
else if (location.hostname === 'www.two.local') {

  const count = await GM.getValue('count', 0);
  console.log(count);
}

})();

推荐阅读