2012-04-09 47 views
4

我正在編寫一個Chrome擴展,它根據當前URL動態更改彈出窗口的內容。每個標籤使用chrome.browserAction.setPopup

我做的background.js這樣的事情,它工作得很好:

if(domains.contains(request.url)){ 
    chrome.browserAction.setPopup({ 
     popup: "tracking.html" 
    }); 
}else{ 
    chrome.browserAction.setPopup({ 
     popup: "nottracking.html" 
    }); 
} 

的問題是,如果切換標籤,在彈出的內容停留標籤之間的相同。處理這個問題的正確策略是什麼?

  • 以某種方式掛鉤選項卡更改事件(如果存在這種可能性)?
  • 將彈出內容的更改限制爲當前選項卡? (我注意到chrome.browserAction.setPopup有一個可選的tabId參數,但文檔有點不足)
  • 還有其他的東西嗎?

非常感謝所有幫助!

回答

4

選項1,綁定一個事件偵聽器:

使用chrome.tabs.onUpdated偵聽URI的變化,其次是chrome.browserAction.setPopup與給定tabId設置彈出對於給定的標籤。例如:

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { 
    if (domains.contains(tab.url)) { 
     chrome.browserAction.setPopup({ 
      tabId: tabId, 
      popup: 'tracking.html' 
     }); 
    } else { 
     chrome.browserAction.setPopup({ 
      tabId: tabId, 
      popup: 'nottracking.html' 
     }); 
    } 
}); 
0

The setpopup parameter's object now supports a tabId value. 你首先需要獲得當前選項卡的數字標識。這不需要額外的權限。

chrome.tabs.query({currentWindow: true, active: true}, function(tabs){ 
    var url = domains.contains(request.url) ? "tracking.html" : "nottracking.html"; 
    chrome.browserAction.setPopup({ 
     popup: url, 
     tabId: tabs[0].id 
    }); 
}); 
+0

也就是說,你可能會對document.location.replace(「foo.html」)感興趣。但我不確定它不適用於所有標籤。 – user2573802 2013-07-12 23:05:49

相關問題