如何检测文档是否重新聚焦? [英] How to detect if document back to focus?
问题描述
我正在使用具有隐藏属性的html5文档对象来检测用户是否已切换到另一个选项卡.如何检查用户是否以相同的方式返回到当前选项卡?
I'm using html5 document object with hidden attribute to detect if user has switched to another tab. How do I check if user has returned to the current tab in the same way?
请参考我的代码:
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分钟后运行.
Interval is made at every 5 seconds to update notification. When current document loses focus, the interval timer is increased to 1 min. So this latest request will only run after 1 min.
如果用户在完成1分钟之前的任何时间返回文档,则他仍未更新通知,因为他必须等待当前请求首先完成.直到那之后,计时器才恢复到5秒.
If the user returns to the document anytime before the 1 minute completed, he still not updated with the notification as he has to wait for the current request to complete first. Only after that the timer back to 5 seconds.
是否可以在1分钟后不等待请求完成就检测用户是否返回到当前文档?
Is it possible to detect if user has back to current document without waiting for request complete after 1 min?
推荐答案
您可以在窗口中使用 blur
和 focus
事件进行检测.
You can use blur
and focus
event in window to detect it.
$(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的结果框中单击以进行测试)
Here is a working example http://jsfiddle.net/uX84X/9/ (Click in result box of jsfiddle to test)
这篇关于如何检测文档是否重新聚焦?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!