2016-11-09 44 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的结果箱测试)