2009-08-03 31 views
3

我試圖檢測用戶何時從當前瀏覽器選項卡切換到另一個選項卡。監聽window.onblur在firefox中工作良好,可以檢測用戶何時將焦點切換到另一個窗口,但當用戶切換到另一個選項卡時似乎不會觸發。但是,從另一個選項卡切換到相關標籤時,似乎會激發onfocus。是否有可能檢測到用戶切換到不同的瀏覽器選項卡?

有沒有辦法檢測用戶何時離開當前標籤?

+0

**更新:**截至2013所有主流瀏覽器提供了所謂的[可視性API]支持(https://developer.mozilla.org/en-US /文檔/網絡/指南/ User_experience/Using_the_Page_Visibility_API?redirectlocale = EN-US&redirectslug = DOM/Using_the_Page_Visibility_API)。看到這裏的示例:http://stackoverflow.com/a/19519701/603003 – ComFreek 2013-10-23 14:07:45

回答

8

顯然,在Firefox中,如果您使用document.onBlur而不是window.onblur作爲事件處理程序,它將適用於製表符切換。

+0

哇,沒想到這樣做,但它是有道理的。謝謝! – 2009-08-03 05:44:18

3

此示例代碼似乎適用於我。當我切換標籤時,我編輯了代碼以顯示一個警告框(請不要這樣做)。它導致了一個無限循環;-)並不得不使用任務管理器關閉FF。

來源:http://www.thefutureoftheweb.com/blog/detect-browser-window-focus

function onBlur() { 
    document.body.className = 'blurred'; 
}; 
function onFocus(){ 
    document.body.className = 'focused'; 
}; 

if (/*@[email protected]*/false) { // check for Internet Explorer 
    document.onfocusin = onFocus; 
    document.onfocusout = onBlur; 
} else { 
    window.onfocus = onFocus; 
    window.onblur = onBlur; 
} 
+1

這是什麼用於Internet Explorer的神奇檢查? – 2009-08-03 10:14:55

相關問題