Javascript to detect if user changes tab


我正在为在线测验写一个网页。我的基本要求是,如果用户更改了标签或打开了新闻窗口,即使没有最小化浏览器,也必须触发一个事件(停止测试) ,例如,如果用户试图从其他窗口/标签查看答案。我该怎么做?

注意: 尽量避免在你的回答中包含一个前沿的 HTML5特性,因为我希望目前所有主流浏览器都支持这个特性。

112385 次浏览

If you are targeting browsers that support it, you can use the Page Visibility API available in HTML5. It doesn't directly detect tab changes, per-say, but visibility changes. Which would include (but not limited to) tab changes.

See https://developer.mozilla.org/en/DOM/Using_the_Page_Visibility_API

You can determine if a tab or window is active by attaching a blur / focus event listener to window.

in jQuery it would be

$(window).focus(function() {
//do something
});


$(window).blur(function() {
//do something
});

quoted from this SO answer: https://stackoverflow.com/a/1760268/680578

Best native function hands down, no jQuery.

document.hasFocus

Check the pen, check what happens when you go to the link and back to the codepen tab.

https://codepen.io/damianocel/pen/Yxxzdj

With jQuery:

$(window).on('focus', function () {


});


$(window).on('blur', function () {


});

$().focus & $().blur are deprecated.

In 2022 you can use an event listener with the visibilitychange event:

document.addEventListener("visibilitychange", (event) => {
if (document.visibilityState == "visible") {
console.log("tab is active")
} else {
console.log("tab is inactive")
}
});

Working on a similar project. This worked the best. On the highest level component which wouldn't normally rerender, add:

  setInterval( checkFocus, 200 );


function checkFocus(){
if(document.hasFocus()==false){
//Do some checking and raise a red flag if this runs during an exam.
}
}

I needed something like this and it seems this behavior is slightly different on each browser.

    if (document.hidden !== undefined) { // Opera 12.10 and Firefox 18 and later support
visibilityChange = "visibilitychange";
} else if (document.mozHidden !== undefined) {
visibilityChange = "mozvisibilitychange";
} else if (document.msHidden !== undefined) {
visibilityChange = "msvisibilitychange";
} else if (document.webkitHidden !== undefined) {
visibilityChange = "webkitvisibilitychange";
} else if (document.oHidden !== undefined) {
visibilityChange = "ovisibilitychange";
}
    

document.addEventListener(visibilityChange, function(event) {
handleVisibilityChange();
}, false);


I have an example you can check: https://jsfiddle.net/jenol/4g1k80jq/33/

window onfocus and onblur work just fine:

window.onfocus = function (ev) {
console.log("gained focus");
};


window.onblur = function (ev) {
console.log("lost focus");
};