检测浏览器标签/窗口是否处于焦点或当前选中

huangapple go评论72阅读模式
英文:

Detect if browser tab/window is focused or currently selected

问题

我正在开发一个知识问答游戏(作为主应用的附加功能),像任何在线知识问答游戏一样,玩家很明显可以通过谷歌搜索来作弊找答案。不过,我想要检测用户是否基本上离开了当前的标签窗口,因为这是一种简单的方式来判断用户在回答问题时是否切换到了其他网站(如果是的话,我将惩罚他们的得分)。

我已经使用了页面可见性API,详细信息可以参考这个回答:https://stackoverflow.com/a/1060034/5579458 - 不过,它只在用户切换标签或最小化/最大化窗口时才有效。如果用户保持标签处于活动状态,但从任务栏最大化了其他程序或将焦点放在另一个窗口上,onchange事件不会被触发。我们该如何编写代码来解决这个问题呢?

英文:

I am building a trivia quiz game (as a side feature of a main app), and as with any online trivia, obviously you can cheat by googling the answer. However, I want to detect basic navigation away from the current/tab window, as this is a simple way of seeing if a user navigated away from the focused site while answering (I will penalize their score if they do).

I have used the Page Visibility API, detailed in this answer https://stackoverflow.com/a/1060034/5579458 - however it only works if the user changes tabs, or minimizes/maximizes the window. The onchange event is not triggered if the user leaves the tab active, but maximizes another program over it from the taskbar or places focus on another window. How can we program this?

答案1

得分: 0

如果visibilityState对您不合适,那么我想唯一的其他选择是onmouseout事件!

window.onmouseout=function(){

  alert('你要去哪里?');

};

如果以上方法不起作用,尝试在文档主体上使用它...

document.body.onmouseout=function(){

  alert('你要去哪里?');

};
英文:

If the visibilityState is no good for you then I guess the only other alternative; which is rather strict, is the onmouseout event!

 window.onmouseout=function(){

  alert('Where are you going?');

 };

Upon this failing, try it on the document body...

 document.body.onmouseout=function(){

  alert('Where are you going?');

 };

huangapple
  • 本文由 发表于 2023年2月24日 13:16:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75552846.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定