[英]How to pass information between 2 tabs running same GreaseMonkey userscript?
我編寫了一個GreaseMonkey (javascript) 用戶腳本,它在指向www.site1.com/stuff
的瀏覽器 (FireFox) 選項卡中運行。 另一個選項卡指向www.site1.com
(沒有stuff
),並且不是第一個的子窗口(例如,不是通過在第一個選項卡上運行的用戶腳本打開的)。 用戶腳本(獨立?)在兩個選項卡上運行。
我希望第一個瀏覽器選項卡上的用戶腳本執行將字符串變量傳遞給第二個瀏覽器選項卡。 雖然GM_setValue
和GM_getValue
在單個用戶腳本中的存儲/檢索工作良好,但該存儲區域似乎無法被用戶腳本的其他執行訪問。 localStorage
遭受同樣的失敗。 對於一個明確的例子:
當用戶腳本檢測到它在www.site1.com/stuff
上運行時,它會將一個值放入存儲中: GM_setValue('parValue', 'aaabbbccc');
在第一個選項卡完全加載並有足夠的時間將此值放入存儲后,將手動打開第二個選項卡。 當用戶腳本檢測到第二個選項卡在www.site1.com
上運行(沒有stuff
)時,代碼會嘗試檢索值: var parVal = GM_getValue('parValue')
。 在我的用戶腳本中,parVal 將有一個null
值; 每個用戶腳本執行似乎使用不同的存儲區域。
我如何實現這個看似簡單的任務,即在以下約束下從公共存儲區域安全/檢索同一用戶腳本的兩個執行:
*的stuff
在第一個選項卡的網址的結尾可以由用戶(書面每一個可以想象的定制獨立userscripts隨意改變stuff
可能是不可能的)。
* 標簽永遠不會有父/子關系,因為它們是獨立生成的(從技術上講,第二個標簽是第一個標簽的孫子,但我不知道這兩個標簽的窗口名稱是什么或如何引用它們在代碼中)。
* 使用在GreaseMonkey 用戶腳本中運行的 javascript
是否有某種可以使用的全局交叉表存儲區域,可以在GreaseMonkey 用戶腳本中實現? 理論上, GM_setValue
應該適用於這種情況嗎? 我花了大量時間研究以下相關 SO 問題的答案,但無法找到適用於上述條件集和/或可以實現到GreaseMonkey 用戶腳本的解決方案: 選項卡或窗口之間的通信, Javascript :在選項卡之間共享數據, https : //superuser.com/questions/1005448/can-a-greasemonkey-script-know-whats-been-loaded-into-another-tab ,使用向所有打開的窗口/選項卡發送消息JavaScript的,
事實證明,“GM_setValue/getValue”確實允許在並行運行相同用戶腳本的 2 個選項卡之間共享信息。 我用以下測試代碼證明了這一點。 我從指向www.google.com
的選項卡開始,收到警報,然后在同一瀏覽器窗口中打開另一個選項卡並將 URL 指向 www.yahoo.com。 該警報表明該值已成功從在google.com
上執行的用戶腳本放置它的存儲中檢索到。
// ==UserScript==
// @name hello world
// @namespace http://www.sharelatex.com
// @include https://www.google.com/*
// @include https://www.yahoo.com/*
// @grant GM_setValue
// @grant GM_getValue
// ==/UserScript==
if (window.location.href.indexOf("google.com") != -1) { // on Google URL
alert("on Google site, storing value");
// you will see the above alert verifying that code understands
// the code is running on the google.com tab
GM_setValue('passValue', 'aabbcc');
} else {
alert("on Yahoo site, retrieving value");
// the above alert will be seen, verifying that the code
// understands the code is running on the yahoo.com tab
var pvalue = GM_getValue('passValue');
alert("The retrieved value is " + pvalue);
// the above alert should show aabbcc, verifying that the
// userscript running on google.com successfully stored the value
// and the script on yahoo.com successfully retrieved it.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.