用于检测用户是否更改选项卡的 Javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10338704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:55:41  来源:igfitidea点击:

Javascript to detect if user changes tab

javascripthtml

提问by Maxsteel


I want to write a webpage for online quiz.Basic requirement i have is that, If the person taking quiz changes tab or opens new window even without minimizing browser, i.e if the person tries to see the answer from some other window/tab , quiz should stop.How can i do that?
P.S: it shouldn't be some very new HTML5 feature.I want it to be supported by all major browser currently.


我想为在线测验编写一个网页。我的基本要求是,如果参加测验的人即使没有最小化浏览器也更改选项卡或打开新窗口,即如果该人试图从其他窗口/选项卡中查看答案,测验应该停止。我该怎么做?
PS:它不应该是一些非常新的 HTML5 功能。我希望当前所有主要浏览器都支持它。

回答by Kristian

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

您可以通过将模糊/焦点事件侦听器附加到窗口来确定选项卡或窗口是否处于活动状态。

in jQuery it would be

在 jQuery 中它会是

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

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

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

引自这个 SO 答案:https: //stackoverflow.com/a/1760268/680578

回答by Matt

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.

如果您的目标浏览器支持它,则可以使用 HTML5 中提供的页面可见性 API。它不直接检测选项卡更改,每个说,但可见性更改。其中将包括(但不限于)选项卡更改。

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

请参阅https://developer.mozilla.org/en/DOM/Using_the_Page_Visibility_API

回答by ptts

Best native function hands down, no jQuery.

最好的原生函数,没有 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

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

回答by 472084

With jQuery:

使用 jQuery:

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

});

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

});

$().focus& $().blurare deprecated.

$().focus&$().blur已弃用。