google-chromegoogle-chrome-extensionbrowser-tab

How can I get the URL of the current tab from a Google Chrome extension?


I'm having fun with Google Chrome extension, and I just want to know how can I store the URL of the current tab in a variable?


Solution

  • Use chrome.tabs.query.

    ManifestV3:

    (async () => {
      // see the note below on how to choose currentWindow or lastFocusedWindow
      const [tab] = await chrome.tabs.query({active: true, lastFocusedWindow: true});
      console.log(tab.url);
      // ..........
    })();
    

    ManifestV2/V3:

    // see the note below on how to choose currentWindow or lastFocusedWindow
    chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
        let url = tabs[0].url;
        // use `url` here inside the callback because it's asynchronous!
    });
    

    You'll need to request tabs or activeTab permission in your extension manifest:

    "permissions": [ ...
       "tabs"
    ]
    

    or

    "permissions": [ ...
       "activeTab"
    ]
    

    Prefer activeTab if your code uses chrome.tabs.query after the user explicitly invoked the extension (clicked its icon or its context menu item or pressed its chrome.commands hotkey) because this permission doesn't add any warnings when installing the extension, unlike tabs that adds Read your browsing history which may scare some users.

    "Current tab" definitions depends on your needs: