43

how to get current tabId from background page? current tabId is the tab that user can see its content.

background.html

<html>
<head>
    <script>

    if(typeof localStorage.state == 'undefined')
        localStorage.state = 'off'
    chrome.browserAction.onClicked.addListener(function(tab) {
        if(localStorage.state == 'on')
        {
            localStorage.state = 'off';
        }
        else
        {
            localStorage.state = 'on';
        }
        chrome.browserAction.setBadgeText({text: localStorage.state, tabId: tab.id});
        chrome.tabs.sendRequest(tab.id, {state: localStorage.state});
        //chrome.tabs.sendRequest(tab.id, {state: localStorage.state});
    });
    </script>
</head>

6 Answers 6

55

getSelected has been deprecated. The new way to do it is:

chrome.tabs.query(
  {currentWindow: true, active : true},
  function(tabArray){...}
)

If you want to perform some callback on the active tab, you can wrap the above as so:

function doInCurrentTab(tabCallback) {
    chrome.tabs.query(
        { currentWindow: true, active: true },
        function (tabArray) { tabCallback(tabArray[0]); }
    );
}

For example

var activeTabId;
doInCurrentTab( function(tab){ activeTabId = tab.id } );
3
  • @neaumusic I have a problem with your edit. It changes a bit too much of the author's code and contains false information (tabArray[0] is not an ID). I'm rolling this back.
    – Xan
    Apr 21, 2015 at 10:13
  • @neaumusic That said, you can definitely post your code as an answer.
    – Xan
    Apr 21, 2015 at 10:40
  • 3
    This totally does not seem to work any more. If I do a console.log(activeTabId); from within the callback (e.g. function(tab){ ... }) I can see that tab.id is set, but then as soon as doInCurrentTab returns, activeTabId remains undefined. Did Google change something that broke this?
    – Doktor J
    Dec 3, 2015 at 7:39
10

Run this in your background page

chrome.tabs.query({active:true,windowType:"normal", currentWindow: true},function(d){console.debug(d);})

or even better

chrome.tabs.query({active:true,windowType:"normal", currentWindow: true},function(d){console.debug(d[0].id);})
3
  • 2
    This will get all active tabs in all windows. So if you have more than one window open you'll get several tabs back.
    – Soviut
    Aug 23, 2013 at 3:28
  • 1
    For the onlookers - it was edited with currentWindow to solve Soviut's issue. Oct 5, 2017 at 12:55
  • Note that just running this code in a background page's devtools window won't return anything. If you run it in a timeout and then switch to regular window, you'll see it return the active tab: setTimeout(() => chrome.tabs.query({ currentWindow: true, active: true }, console.log), 2000)
    – jdunning
    May 16, 2020 at 1:13
6

According to the official documentation: Manifest V3 (promise), which will be enforced since Jan 2023 https://developer.chrome.com/docs/extensions/reference/tabs/#get-the-current-tab

async function getCurrentTab() {
  let queryOptions = { active: true, lastFocusedWindow: true };
  let [tab] = await chrome.tabs.query(queryOptions);
  return tab;
}
3

Many API methods interpret null as a current tab. chrome.tabs.sendRequest is one of them.

Otherwise:

chrome.tabs.getSelected(null, function(tab) { ... })
1
2

If you have tabs user permission, the query method is this: chrome.tabs.query


getCurrentWindowActiveTabIndex().then(tabIndex => {
    // do something
});

// asnyc getter, not just a regular 'thunk'
function getCurrentWindowActiveTabIndex () {
    return new Promise((resolve, reject) => {
        chrome.tabs.query({
            currentWindow: true,
            active: true,
        }, (currentWindowActiveTabs = []) => {
            if (!currentWindowActiveTabs.length) reject();
            resolve(currentWindowActiveTabs[0].index);
        });
    });
}
1
  • 3
    A little bit of explanation of what this code does, and why is this answer better than others, would be welcome.
    – Xan
    Apr 23, 2015 at 7:00
2

For manifest version 3 Here :

chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
  console.log(tabs[0].url);
  my_tabid=tabs[0].id;
  alert(my_tabid);
});
//then use it, my_tabid 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.