0

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
        }
    ],
}
sdfsdf
  • 5,052
  • 9
  • 42
  • 75
  • 1
    The code is correct. You need to reload the extension after editing manifest.json. If it doesn't help, open chrome://policy and see if it has ExtensionSettings with runtime_blocked_hosts inside. – wOxxOm Aug 10 '22 at 07:00
  • Are you right-clicking the extension icon to "Inspect pop-up window?" Based on my observation, clicking "Inspect pop-up window" on the extension icon's context menu will cause the active tab to miss a lot of properties. My current workaround is open the popup first, right click on the pop-up window, and then "Insepct". Later, you can F5 or Ctrl-R reload that window in case you want to debug the loading logic. – Chuanqi Sun Feb 05 '23 at 20:26

1 Answers1

0

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