Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get current tabId from background page

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>

like image 865
wiiman Avatar asked Sep 05 '11 02:09

wiiman


4 Answers

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 } );
like image 105
Arithmomaniac Avatar answered Nov 20 '22 17:11

Arithmomaniac


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);})
like image 36
mc. Avatar answered Nov 20 '22 17:11

mc.


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

Otherwise:

chrome.tabs.getSelected(null, function(tab) { ... })
like image 3
serg Avatar answered Nov 20 '22 17:11

serg


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);
        });
    });
}
like image 1
neaumusic Avatar answered Nov 20 '22 18:11

neaumusic