如何从后台页面获取当前tabId? current tabId是用户可以看到其内容的标签。
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>
答案 0 :(得分:44)
getSelected
已deprecated。新方法是:
chrome.tabs.query(
{currentWindow: true, active : true},
function(tabArray){...}
)
如果要在活动选项卡上执行某些回调,可以将上述内容包装为:
function doInCurrentTab(tabCallback) {
chrome.tabs.query(
{ currentWindow: true, active: true },
function (tabArray) { tabCallback(tabArray[0]); }
);
}
例如
var activeTabId;
doInCurrentTab( function(tab){ activeTabId = tab.id } );
答案 1 :(得分:6)
在后台页面中运行
chrome.tabs.query({active:true,windowType:"normal", currentWindow: true},function(d){console.debug(d);})
甚至更好
chrome.tabs.query({active:true,windowType:"normal", currentWindow: true},function(d){console.debug(d[0].id);})
答案 2 :(得分:3)
许多API方法将null
解释为当前标签。 chrome.tabs.sendRequest
就是其中之一。
否则:
chrome.tabs.getSelected(null, function(tab) { ... })
答案 3 :(得分:0)
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);
});
});
}