是否可以检测当前页面是否在 alt-tab 中? 此代码仅在浏览器中打开新选项卡时有效:
(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";
//console.log(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"});
})();
但是这段代码既没有检测到浏览器的新窗口,也没有检测到任何其他程序的 alt-tab。有可能检测到吗?还是在 jQuery 中?
编辑 新页面意味着 Ctrl(cmd)+N(新窗口)热键。上面的代码无法检测到这一点。 Alt(cmd)+tab 到另一个程序 - 也无法检测到。 上面的代码只能检测Ctrl(cmd)+T (new tab)
编辑
我想检测用户何时从另一个应用程序返回我的站点。也就是说,如果用户关闭任何选项卡(例如,通过 Ctrl+W)并返回到我的站点,我可以使用上面的脚本检测到此操作。但是,如果用户从另一个应用程序(例如,通过 Alt+Tab)返回到我的站点,则脚本将不起作用,因为 window.onfocus
不会被触发!也就是说,
window.onpageshow =
window.onpagehide = window.onfocus = window.onblur
不适用于 Alt+Tab 操作。是不是更清楚了?
最佳答案
您可以简单地使用 onfocus
事件 window
,例如:
window.onfocus = function() {
console.log('Got focus');
}
如果需要,您也可以使用 onblur
进行更严格的处理。
关于javascript - 使用纯 JS 或 jQuery 使用 Alt-Tab 检测浏览器页面窗口何时失去焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34383528/