有没有办法检测浏览器窗口当前是否处于活动状态?我有定期执行活动的JavaScript。当用户没有看到该站点时(即窗口或选项卡没有焦点),最好不要运行。有没有办法使用JavaScript?我的参考点:如果您使用的窗口未处于活动状态,则Gmail聊天会播放声音。
4 回答
千万里不及你
TA贡献1784条经验 获得超9个赞
自从最初撰写此答案以来,由于W3C ,新规范已达到推荐状态。在网页浏览权限API(在MDN)现在允许当一个页面被隐藏到用户我们更准确地检测。
目前的浏览器支持
Chrome 13+
Internet Explorer 10+
Firefox 10+
Opera 12.10+ [ 阅读笔记 ]
以下代码使用API,回退到不兼容的浏览器中不太可靠的模糊/焦点方法。
(function() {
var hidden = "hidden";
// Standards:
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 and lower:
else if ("onfocusin" in document)
document.onfocusin = document.onfocusout = onchange;
// All others:
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";
}
// set the initial state (but only if browser supports the Page Visibility API)
if( document[hidden] !== undefined )
onchange({type: document[hidden] ? "blur" : "focus"});})();onfocusin并且onfocusout是IE 9及更低版本所必需的,而所有其他人都使用onfocus和onblur使用onpageshow和的iOS除外onpagehide。
绝地无双
TA贡献1946条经验 获得超4个赞
我会使用jQuery因为那样你所要做的就是:
$(window).blur(function(){
//your code here});$(window).focus(function(){
//your code});或者至少它对我有用。
添加回答
举报
0/150
提交
取消
