简体   繁体   English

Chrome 扩展:从弹出窗口中获取活动 url

[英]Chrome Extension: getting active url from popup undefined

I am trying to get the tab url when my Chrome Extension's popup is open.当我的 Chrome 扩展程序的弹出窗口打开时,我正在尝试获取选项卡 url。 I've looked at other answers and came up with this:我查看了其他答案并想出了这个:

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

The Promise resolves to Promise 解析为

{
    "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
}

The tab's url is undefined !选项卡的 url undefined

I've tried adding "tabs" and "activeTab" to my manifest v3's permissions array but still the url is undefined.我已经尝试将"tabs""activeTab"添加到我的清单 v3 的permissions数组中,但 url 仍然未定义。 Help!帮助!

EDIT:编辑:

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
        }
    ],
}

How to wait for the chrome.tabs.query to return tab id 如何等待 chrome.tabs.query 返回选项卡 ID

The answer to this one would be a solution to your issue if you change it from id to url, posted by Lakshya Thakur.如果您将其从 id 更改为 url(由 Lakshya Thakur 发布),则此问题的答案将是您的问题的解决方案。

This did solve mine when I was trying to get the current tabs url into a chrome extension.当我试图将当前标签 url 转换为 chrome 扩展时,这确实解决了我的问题。

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM