userscripts - GM_getTab(cb) 如何工作?

标签 userscripts tampermonkey

似乎没有关于这些功能如何工作的任何信息。我想这些是 Tampermonkey 独有的功能?
看起来它们旨在允许当前运行的 Tampermonkey 脚本之间进行通信;不断轮询 GM_Value 存储以进行更改的替代方法。这是一个非常有趣的想法。

但我不知道如何使用它们;他们接受什么值(value),你得到什么样的对象?
您如何使用这三个功能,我的目的是否正确?

GM_getTab(cb)
Get a object that is persistent as long as this tab is open.

GM_saveTab(tab)
Save the tab object to reopen it after a page unload.

GM_getTabs(cb)
Get all tab objects in an array to communicate with other scrips instances.

(http://forum.tampermonkey.net/viewtopic.php?f=16&t=74)

最佳答案

我从未尝试过使用它们,但是查看代码似乎能够从每个选项卡存储/获取您想要的任何内容,并且还可以通过所有选项卡以这种方式存储所有内容。

在两个 Chrome 控制台上,我运行了以下命令:

var this_tab_data, all_tabs, n;

GM_getTab(function (o) {
    this_tab_data = o;
    n = this_tab_data.rand = Math.random();
    GM_saveTab(this_tab_data);
    console.info(this_tab_data);

    GM_getTabs(function (db) {
        all_tabs = db;
        console.info(n);
        for (var i in all_tabs) {
            if (all_tabs[i].rand === n) console.info("I bet I am the tab named: " + i);
            else console.info("Other tab: " + i + " has value: " + all_tabs[i].rand);
        }
    });
});

结果(在选项卡 2 中):
Object {rand: 0.9303610376082361}
VM779:11 0.9303610376082361
VM779:14 Other tab: 366 has value: 0.417106909211725
VM779:13 I bet I am the tab named: 371

I added access in the chrome console using this user script, (based on the instructions on the indicated @match page):

// ==UserScript==
// @name       My Fancy New Userscript
// @namespace  http://use.i.E.your.homepage/
// @version    0.1
// @description  enter something useful
// @match      http://stackoverflow.com/questions/14059078/use-the-tampermonkey-api-from-the-chrome-console
// @copyright  2012+, You
// ==/UserScript==

unsafeWindow.GM_getTab = GM_getTab;
unsafeWindow.GM_saveTab = GM_saveTab;
unsafeWindow.GM_getTabs = GM_getTabs;

作为旁注,我看到在关闭设置它的选项卡后,这些数据仍然可以通过 GM_getTabs() 访问。我不确定我会指望这一点,但我可能会尽量减少我留下的东西。

关于userscripts - GM_getTab(cb) 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25793331/

相关文章:

jquery - @require-ing jQuery 覆盖页面的 $ 变量

javascript - 阻止执行特定的内联脚本标签

jquery - 使用外部 CSS 文件将 jQuery UI 添加到 Greasemonkey 脚本失败

javascript - 检测特定文本框是否具有焦点

javascript - Greasemonkey 脚本来监控网站更改

javascript - Chrome/Tampermonkey 用户脚本存储在文件系统的什么位置?

javascript - 从 Google Chrome 控制台访问用户脚本变量

javascript - Tampermonkey 脚本根据页面打开和呈现的方式给出不同的结果? (内容相同)

javascript - xmlhttprequest - 异常 101 错误

google-chrome - 如何在浏览器解析原始 HTML 之前使用 Greasemonkey/Tampermonkey 对其进行编辑