2016-11-09 45 views
1

我使用帶有隱藏屬性的html5文檔對象來檢測用戶是否已切換到另一個選項卡。如何檢查用戶是否以同樣的方式返回到當前選項卡?如何檢測文檔是否重新聚焦?

請參考我的代碼:

var PERIOD_NOT_VISIBLE = 60000; 
var PERIOD_VISIBLE = 5000;    
var timestring = 0; 

(function callThis(timestring) { 

    //update notification 

    timer = setTimeout(function() { 

    callThis(timestring);     
    }, (document.hidden) ? PERIOD_NOT_VISIBLE : PERIOD_VISIBLE); 

})(); 

間隔爲每5秒內更新通知。當前文檔失去焦點時,間隔計時器增加到1分鐘。所以這個最新的請求只會在1分鐘後運行。

如果用戶在完成1分鐘之前的任何時候返回到文檔,他仍未更新通知,因爲他必須等待當前請求先完成。只有在這之後,定時器才能恢復到5秒。

是否有可能在1分鐘後檢測用戶是否已經返回當前文檔而無需等待請求完成?

+1

你這樣做:https://developer.mozilla.org/en-US/docs/Web/API/ Page_Visibility_API – vsync

回答

3

您可以在窗口中使用blurfocus事件來檢測它。

$(window).on("blur", function() { 
    // do whatever you want 
    $("body").append("<p>Windows lost focus</p>"); 
}); 
$(window).on("focus", function() { 
    // do whatever you want 
    $("body").append("<p>Windows got focus</p>"); 
}); 

這裏是一個工作示例http://jsfiddle.net/uX84X/9/(點擊的jsfiddle的結果箱測試)