2011-09-05 141 views
19

如何從背景頁面獲取當前tabId? 當前tabId是用戶可以看到其內容的選項卡。如何從背景頁面獲取當前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> 

回答

2

許多API方法解釋null作爲當前選項卡。 chrome.tabs.sendRequest就是其中之一。

否則:

chrome.tabs.getSelected(null, function(tab) { ... }) 
37

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 }); 
+0

@neaumusic我有你的編輯有問題。它稍微改變了作者的代碼並且包含了錯誤的信息('tabArray [0]'不是一個ID)。我正在回滾。 – Xan

+0

@neaumusic這就是說,你絕對可以發佈你的代碼作爲答案。 – Xan

+0

這完全不似乎工作了。如果我在回調函數(例如'function(tab){...}')中執行'console.log(activeTabId);',我可以看到tab.id已設置,但只要doInCurrentTab返回,activeTabId仍未定義。谷歌是否改變了這一切? –

4

在您的背景頁面中運行此操作

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

這將獲得所有窗口中的所有活動選項卡。所以如果你有多個窗口打開,你會得到幾個標籤。 – Soviut

+0

對於圍觀者 - 它是用'currentWindow'編輯來解決Soviut的問題。 –

0

chrome.tabs.query

my chrome extension using chrome.tabs.query


function onNextTabDetermined (callback) { 
    chrome.tabs.query({ 
     currentWindow: true, 
     active: true 
    }, function (currentTabs) { 
     var nextTabIndex = (currentTabs[0].index + (forward ? 1 : -1)); 
     if (nextTabIndex === -1) { 
      chrome.tabs.query({ 
       "currentWindow": true 
      }, function (allTabs) { 
       callback(allTabs[allTabs.length - 1]); 
      }); 
     } else { 
      chrome.tabs.query({ 
       "index": nextTabIndex, 
       "currentWindow": true 
      }, function (nextTabs) { 
       if (nextTabs[0]) { 
        callback(nextTabs[0]); 
       } else { 
        chrome.tabs.query({"index": 0}, function (nextTabs) { 
         callback(nextTabs[0]); 
        }); 
       } 
      }); 
     } 
    }); 
}; 
+1

對於這段代碼做些什麼的解釋,以及爲什麼這個答案比別人更好,這是值得歡迎的。 – Xan