简体   繁体   中英

Chrome Extension: getting active url from popup undefined

I am trying to get the tab url when my Chrome Extension's popup is open. 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

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

I've tried adding "tabs" and "activeTab" to my manifest v3's permissions array but still the url is undefined. 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

The answer to this one would be a solution to your issue if you change it from id to url, posted by Lakshya Thakur.

This did solve mine when I was trying to get the current tabs url into a chrome extension.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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