我看过这个:
How to tell if browser/tab is active
和
Is there a reliable way to determine if a browser tab or window is inactive or not in focus?
第一个链接为现代浏览器提供解决方案,但在IE7 / 8中不起作用。这两个问题都相当陈旧。是否有解决方案来确定访问者是否正在查看他们的打开标签?
我尝试过的几乎所有内容都适用于Chrome。但IE7失败了。
我只想设置一个全局变量,说明是否正在查看该页面。
即
var isActive = true;
$(window).focus(function() {
isActive = true;
});
$(window).blur(function() {
isActive = false;
});
// test
setInterval(function () {
console.log(window.isActive ? 'active' : 'inactive');
}, 1000);
答案 0 :(得分:7)
经过大量谷歌搜索...然后再多一些......然后再多一点...... 4个小时左右我终于发现这个链接隐藏在互联网的深处。这些评论表明存在一个小错误,但它对我需要的东西很好。
http://www.thefutureoftheweb.com/blog/detect-browser-window-focus
var isActive = true;
function onBlur() {
isActive = false;
};
function onFocus(){
isActive = true;
};
if (/*@cc_on!@*/false) { // check for Internet Explorer
document.onfocusin = onFocus;
document.onfocusout = onBlur;
} else {
window.onfocus = onFocus;
window.onblur = onBlur;
}
答案 1 :(得分:1)
略有不同,但this was marked as the answer表明它有效,这是一个需要的延迟。不是很优雅,但如果它有效。