【问题标题】:Chrome Extension: getting active url from popup undefinedChrome 扩展程序:从未定义的弹出窗口中获取活动 url
【发布时间】:2022-08-23 01:22:40
【问题描述】:

当我的 Chrome 扩展程序的弹出窗口打开时,我正在尝试获取选项卡 URL。我查看了其他答案并想出了这个:

export const getTab = () => {
    return new Promise((res) => {
        chrome.tabs.query({ currentWindow: true, active: true }, (tabs) => {
            console.log(\'tabs:\', tabs);
            res(tabs[0]);
        });
    });
};

承诺解决

{
    \"active\": true,
    \"audible\": false,
    \"autoDiscardable\": true,
    \"discarded\": false,
    \"groupId\": -1,
    \"height\": 624,
    \"highlighted\": true,
    \"id\": 2297,
    \"incognito\": false,
    \"index\": 1,
    \"mutedInfo\": {
        \"muted\": false
    },
    \"openerTabId\": 128,
    \"pinned\": false,
    \"selected\": true,
    \"status\": \"complete\",
    \"width\": 160,
    \"windowId\": 1
}

标签的网址是undefined

我尝试将\"tabs\"\"activeTab\" 添加到我的清单v3 的permissions 数组中,但url 仍然未定义。帮助!

编辑:

manifest.json

{
    \"manifest_version\": 3,
    \"name\": \"Test\",
    \"version\": \"1.0.0\",
    \"action\": {
        \"default_title\": \"Test\",
        \"default_popup\": \"popup.html\"
    },
    \"permissions\": [\"tabs\"],
    \"background\": {
        \"service_worker\": \"src/background.js\",
        \"type\": \"module\"
    },
    \"content_scripts\": [
        {
            \"js\": [\"src/contentScript.js\"],
            \"matches\": [\"<all_urls>\"],
            \"run_at\": \"document_start\",
            \"all_frames\": true
        }
    ],
}
  • 代码是正确的。您需要在编辑 manifest.json 后重新加载扩展。如果没有帮助,请打开 chrome://policy 并查看它是否有 ExtensionSettings 和 runtime_blocked_hosts 里面。

标签: javascript google-chrome-extension


【解决方案1】:

How to wait for the chrome.tabs.query to return tab id

如果您将其从 id 更改为 url,这个问题的答案将是您的问题的解决方案,由 Lakshya Thakur 发布。

function getTabID() {
    return new Promise((resolve, reject) => {
        try {
            chrome.tabs.query({
                active: true,
            }, function (tabs) {
                resolve(tabs[0].id);
            })
        } catch (e) {
            reject(e);
        }
    })
}

//function where you need it
async function something() {
    let responseTabID = await getTabID();
}

【讨论】:

    猜你喜欢
    • 2016-10-24
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    • 2014-11-19
    • 2023-01-02
    • 2011-03-03
    • 1970-01-01
    • 2011-09-27
    相关资源
    最近更新 更多