可以使用Page Visibility API来检测页面是否为当前的窗口。当浏览器不兼容page visibility api时,可以监听window的blur/focus事件.
Page Visibility API兼容的浏览器:
- Chrome 13+
- Internet Explorer 10+
- Firefox 10+
- Opera 12.10+
代码如下:
(function() {
var hidden = "hidden";
// 标准浏览器:
if (hidden in document)
document.addEventListener("visibilitychange", onchange);
else if ((hidden = "mozHidden") in document)
document.addEventListener("mozvisibilitychange", onchange);
else if ((hidden = "webkitHidden") in document)
document.addEventListener("webkitvisibilitychange", onchange);
else if ((hidden = "msHidden") in document)
document.addEventListener("msvisibilitychange", onchange);
// IE 9以下版本:
else if ("onfocusin" in document)
document.onfocusin = document.onfocusout = onchange;
// 其他浏览器使用blur/focus时间:
else
window.onpageshow = window.onpagehide
= window.onfocus = window.onblur = onchange;
function onchange (evt) {
var v = "visible", h = "hidden",
evtMap = {
focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h
};
evt = evt || window.event;
if (evt.type in evtMap)
document.body.className = evtMap[evt.type];
else
document.body.className = this[hidden] ? "hidden" : "visible";
}
// 对支持Page Visibility API的浏览器设置初始状态
if( document[hidden] !== undefined )
onchange({type: document[hidden] ? "blur" : "focus"});
})();