簡體   English   中英

如何使 GM_getValue 存在於 Firefox 上的 Greasemonkey 中?

[英]How to make GM_getValue existent in Greasemonkey on Firefox?

被欺騙的候選對象是以前的 GM 版本。 問題是各地不同范圍,其中userscripts可以運行,如描述可能的地方在這里 然而,如所描述這里,這個功能目前對於無證的Greasemonkey 4.0。

我有這個 Greasemonkey 演示腳本:

// ==UserScript==
// @name         GM_getValue, GM_setValue don't work demo
// @version      0.2
// @author       You
// @include      /^https:\/\/stackoverflow.com/$/
// @grant        GM_getValue
// @grant        GM_setValue
// @run-at       document-end
// ==/UserScript==

console.log('script started');
var id = GM_getValue('testName', 0);
console.log('got ' + id);
id++;
GM_setValue('testName', id);

使用https://stackoverflow.com/調用它,很明顯它被調用了。

但是,我在控制台上收到此錯誤:

Script error:  
ReferenceError: GM_getValue is not defined
Stack trace:
userScript@user-script:demosrv/GM_getValue%2C%20GM_setValue%20don%27t%20work%20demo:372:5
scopeWrapper@user-script:demosrv/GM_getValue%2C%20GM_setValue%20don%27t%20work%20demo:381:9
@user-script:demosrv/GM_getValue%2C%20GM_setValue%20don%27t%20work%20demo:361:17

我已經GM_{get,set}Value了很多文檔,但似乎GM_{get,set}Value根本不想存在。

為什么會這樣? 如何讓它工作?

我正在使用 Firefox。

GM_getValueGM_setValue現在在 GreaseMonkey 中已過時。 正確的方法是GM.setValueGM.getValue

GreaseMonkey 文檔經常使用舊的 API 調用名稱,這是其中的一個連續錯誤。 可能它沒有正確更新。

正如這里的文檔所說,GM 函數可以在不同的范圍內運行。 不幸的是,直到現在我才找到任何信息,哪些范圍存在以及我們如何在它們之間切換。

網絡上許多地方使用GM_getValue的舊引用都已過時。

重要的事情:

  • GM_getValue是具有返回值的函數,而GM.getValueGM.setValue返回Promise s。
  • 您可以像在舊的、漂亮的版本中一樣使用它們,使用await調用。

遠程鏈接上的此示例有效:

// ==UserScript==
// @name        Greasemonkey set-and-get Example
// @description Stores and logs a counter of executions.
// @grant       GM.setValue
// @grant       GM.getValue
// ==/UserScript==

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

  // Note awaiting the set -- required so the next get sees this set.
  await GM.setValue('count', count_before + 1);

  // Get the value again, just to demonstrate order-of-operations.
  let count_after = await GM.getValue('count');

  console.log('Greasemonkey set-and-get Example has run', count_after, 'times');
})();

但是,仍然沒有關於范圍以及我們如何與它們交互的更清晰的文檔。

看來,至少有兩個作用域:

  • 在其中之一中,您可以操作 DOM,但不能訪問GM.* API。
  • 另一方面,您可以訪問GM.* API(因此,您可以創建腳本本地持久存儲),但無權訪問 DOM。
  • 在作用域之間,我們可以通過異步調用進行通信。
  • 為什么這個麻煩會增加安全性,可能連 GM 開發者都說不出來。

因此,為 4.0 開發新的 GreaseMonkey 腳本的方法是從他們的示例腳本開始,然后遵循增量試錯路徑。


擴展:我發現的另一個麻煩:腳本中await的存在似乎使油脂猴忽略了整個腳本等。 在示例中,它似乎不會發生,但在更復雜的腳本中,它會發生。 我沒有調試太深 - 我只是忽略了await並以舊方式使用 Promises ( GM.getValue("myValue").then(function(myValue) { ... }); )。 它使代碼更糟糕,但也是如此。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM