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>

wiiman
  • 431
  • 1
  • 4
  • 3

6 Answers6

54

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 } );
Arithmomaniac
  • 4,604
  • 3
  • 38
  • 58
  • @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 '15 at 10:13
  • @neaumusic That said, you can definitely post your code as an answer. – Xan Apr 21 '15 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 03 '15 at 07:39
9

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);})
mc.
  • 539
  • 6
  • 15
  • 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 '13 at 03:28
  • 1
    For the onlookers - it was edited with `currentWindow` to solve Soviut's issue. – Pimp Trizkit Oct 05 '17 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 '20 at 01: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;
}
elier
  • 439
  • 4
  • 12
3

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

Otherwise:

chrome.tabs.getSelected(null, function(tab) { ... })
serg
  • 109,619
  • 77
  • 317
  • 330
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);
        });
    });
}
neaumusic
  • 10,027
  • 9
  • 55
  • 83
  • 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 '15 at 07:00
1

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 
Hakan
  • 240
  • 3
  • 4