2011-05-19 94 views
2

我正在做一個包含內容腳本,做下面的一個Chrome擴展:檢測哪個選項卡/正集中窗口谷歌瀏覽器

  • 內容腳本注入到每一頁
  • 定期調用功能「a」每5秒
  • 如果頁面處於焦點狀態,則調用函數「b」。

理想情況下,應該爲每個選項卡調用函數「a」,但函數「b」只會針對所關注的選項卡調用。

我已經研究過這樣做的幾種方法,我發現的最接近的解決方案是這樣的: How to detect when a tab is focused or not in Chrome with Javascript?

然而,當我試圖用outerHeight/innerHeight方法,它給了我一些很奇怪結果。當窗口沒有焦點時,我爲outerHeight取0。這對我來說似乎更像是一個bug,所以我不確定我是否可以使用它來確定選項卡是否不在焦點。

有沒有人有這個好的解決方案?

回答

5

不知道內容的腳本唯一的解決辦法,但是可以使用的後臺頁面的幫助來輕鬆完成:

content_script.js:

function task() { 
    chrome.extension.sendRequest("is_selected", function(isSelected) { 
     if(isSelected) { 
      //this tab in focus 
     } else { 
      //not in focus 
     } 
    }); 
} 
setInterval(task, 5000); 

background.html:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { 
    if(request == "is_selected") { 
     chrome.tabs.getSelected(null, function(tab){ 
      if(tab.id == sender.tab.id) { 
       sendResponse(true); //in focus (selected) 
      } else { 
       sendResponse(false); //not in focus 
      } 
     }); 
    } 
}); 
+0

謝謝了很多serg :) – 2011-05-19 19:53:49

+0

輝煌。比document.hasFocus()更可靠 – toddmo 2016-09-19 21:26:13

相關問題