首页 > 解决方案 > Tampermonkey 在特定选项卡上运行脚本

问题描述

我正在学习 Tempermonkey 和它的用户脚本。我有一些问题。

我想为所有 firefox 打开的容器运行一个脚本,但是这个脚本必须根据它运行的容器选项卡具有不同的设置。像某些函数中的某些数据和不同的条件。

我尝试使用GM_getTab它,但由于某些原因它向我发送了一个空对象。

// @grant GM_getTab

GM_getTab(function (e) {
    console.log(e); // 'e is empty in console and in debug window either'
});

那么基本上如何使用这个功能来完成我的任务呢?

PS Firefox:便携式 93.0(64 位)

标签: tampermonkeyuserscripts

解决方案


天哪,为什么总是这样,只是问了这个问题,然后在接下来的 10 分钟内找到了解决方案:D

所以解决方案是:

(async () => {
    const tabObj = await GM.getTab();

    // You first have to define ID for all tabs you need, then just comment this part
    tabObj.id = Math.random();
    GM_saveTab(tabObj); // update the object

    // get all stored objects
    const tabsDatabase = await GM.getTabs();
    const dbL = Object.keys(tabsDatabase).length;

    console.log('Script-owned tab:', tabObj); // Current tab
    console.log('Script-owned tabs count:', tabsDatabase); // All opened tabs
})();

推荐阅读