How do you use chrome.tabs.getCurrent to get the page object in a Chrome extension?

Viewed 45639

The code is meant to output the current tab object for the page the user is viewing to the console but it just outputs undefined. It's run from within a browser action page.

chrome.tabs.getCurrent( function(tab){
    console.log(tab);
} );

I've looked at the documentation and as far as I can tell the code seems to match what it says.

5 Answers

Since chrome.tabs is only available in background or popup script and background script is not active in any tab, chrome.tabs.getCurrent() always return undefined.

Instead, we can retrieve the active Tab object from the second argument of any message listener callback. For example,

browser.runtime.onMessage.addListener((message, sender) => {
  console.log('Active Tab ID: ', sender.tab.id);
});

May be undefined if called from a non-tab context (for example, a background page or popup view).

It looks like you should use this code not in bg.js but rather in cs.js.

If you encounter this issue, problem can be caused by using chrome.tabs.getCurrent() in wrong place. You can't use chrome.tabs in content scripts. But you can use it in background or options scripts.

This example requires Manifest due to the use of Promises. Additionally, content scripts cannot use tabs.query.

Related