how to get current tabId from background page? current tabId is the tab that user can see its content.
background.html
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);})
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 } );
Many API methods interpret null
as a current tab. chrome.tabs.sendRequest
is one of them.
Otherwise:
chrome.tabs.getSelected(null, function(tab) { ... })
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);
});
});
}