Search code examples
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:

    • currentWindow: true always uses the window where your popup was initially shown regardless of whether the user has switched to another window after opening the popup. There's usually no difference at the start of the popup script, because it runs while the original window is still focused. The term currentWindow means "currently running extension code's window".

    • lastFocusedWindow: true uses the actually focused window at the time of the call (typically the topmost window), which may differ from the original window showing the popup in case the user has switched to another window (or your extension opened a new window) and chrome.tabs.query is called after that e.g. in a click listener for a button in the popup.

    • A chrome.runtime.onMessage listener should normally use sender.tab from the sender parameter.