如何检测文档是否回焦

How to detect if document back to focus?

本文关键字:文档 是否 检测 何检测      更新时间:2023-09-26

我使用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分钟?

您可以使用窗口中的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的结果框进行测试)