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>
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 } );
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);})
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);
});
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With