检测浏览器选项卡是否处于活动状态或用户是否已切换 [英] Detect if browser tab is active or user has switched away
本文介绍了检测浏览器选项卡是否处于活动状态或用户是否已切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何检测用户是否正在切换到其他浏览器标签?
How can I detect if a user is switching to another browser tab?
目前,我有:
$(window).on("blur focus", function (e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
$('.message').html('<div class="alert alert-error">Oops. You navigated away from the ads <a id="start" class="butt green">Resume</a></div>');
var myDiv = $("#bar");
myDiv.clearQueue();
myDiv.stop();
clearInterval($timer);
$timer = null;
break;
case "focus":
// do work
break;
}
}
$(this).data("prevType", e.type);
});
但这仅在用户最小化活动窗口时才有效。
But that only works when the user is minimizing the active window.
推荐答案
现在我们可以使用 visibility API 。
为了处理不同的浏览器特定语法,我把它做得很小代码:
To deal with the different browser-specific syntaxes, I made this small code :
var vis = (function(){
var stateKey, eventKey, keys = {
hidden: "visibilitychange",
webkitHidden: "webkitvisibilitychange",
mozHidden: "mozvisibilitychange",
msHidden: "msvisibilitychange"
};
for (stateKey in keys) {
if (stateKey in document) {
eventKey = keys[stateKey];
break;
}
}
return function(c) {
if (c) document.addEventListener(eventKey, c);
return !document[stateKey];
}
})();
用法:
var visible = vis(); // gives current state
vis(aFunction); // registers a handler for visibility changes
示例:
vis(function(){
document.title = vis() ? 'Visible' : 'Not visible';
});
这篇关于检测浏览器选项卡是否处于活动状态或用户是否已切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文