在 JavaScript 中检测选项卡/窗口激活
当我在 Firefox 中激活该选项卡时,Google+ 似乎会检查通知更新。
每次我激活它时,它都会显示“0”,但此后几秒钟内会更改为许多新通知。
允许利用该事件的机制是什么?有专门的 DOM 事件吗?或者他们是否使用诸如 onmouseover 处理程序之类的东西,并且只考虑任何类型的活动作为选项卡激活的充分指标?
It seems that Google+ checks for notification updates when I activate the tab in Firefox
It'd show "0" every time I activate it, but change to a number of new notifications in a couple of seconds after that.
What's the mechanism allowing to tap into that event? Is there a specific DOM event for that? Or are they using something like onmouseover handler and just consider any kind of activity to be a sufficient indicator of tab activation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有一个页面可见性文档,其中描述了document.onvisibilitychange 事件处理程序。
用途
There is Page visibility document, which describes document.onvisibilitychange event handler.
The usage
只是猜测,因为我还没有所有相关的浏览器可用于测试。
在
窗口
上使用focus
事件怎么样?每当用户单击某处时都会调用此函数,但也会在切换选项卡时调用。要区分用户在页面上的操作和用户切换到页面的操作,您可以检查事件的explicitOriginalTarget
是否指向window
。Just a guess because I haven't all relevant browsers available for testing.
What about using the
focus
event on thewindow
. Whenever a user clicks somewhere this is invoked but also on switching of tabs. To distinguish between a user's actions on the page and a user switching to the page you could check if the event'sexplicitOriginalTarget
points to thewindow
.不幸的是,没有 100% 准确的解决方案
onvisibilitychange
在选项卡更改时正确触发,但在窗口更改 (ALT+TAB) 时不触发使用 ALT+TAB 切换程序/窗口或单击时不触发visibilitychange事件在任务栏中window.onfocus
当文档获得焦点时触发。如果选项卡的焦点已经在网页内,那么它会按预期工作,然后当窗口或选项卡获得焦点时它会正确触发。但是,如果您将焦点放在 URL 栏或控制台中,则您已经“失去焦点”,并且当您离开窗口或选项卡时,返回,您将保持“失焦”状态,因此在您单击页面内部或通过 TAB 键导航到页面之前,此事件不会触发
您可以在下面测试每个事件如何触发(单击白色 iframe 内部以测试 onfocus/关于模糊事件)
Unfortunately there's no 100% accurate solution
onvisibilitychange
correctly triggers on tab changes, but does not trigger on window changes (ALT+TAB) visibilitychange event is not triggered when switching program/window with ALT+TAB or clicking in taskbarwindow.onfocus
triggers when the document becomes focused. This works as expected if the tab's focus is already inside the web page, then it correctly triggers when window or tab becomes focused.But if you have the focus on the URL bar, or in the console, you are already "out of focus", and when you get out of the window or tab and return, you will remain "out of focus", so this event won't trigger until you click inside the page, or navigate into it through TAB key
You can test below how each event triggers (click inside the white iframe to test onfocus/onblur events)