检测JavaScript中的标签页/窗口激活 [英] Detect tab/window activation in JavaScript

查看:61
本文介绍了检测JavaScript中的标签页/窗口激活的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Firefox中激活标签页时,似乎Google+会检查通知更新

It seems that Google+ checks for notification updates when I activate the tab in Firefox

每次我将其显示为"0",但在此后的几秒钟内更改为许多新的通知.

It'd show "0" every time I activate it, but change to a number of new notifications in a couple of seconds after that.

允许使用该事件的机制是什么?是否有特定的DOM事件?还是他们使用类似 onmouseover 的处理程序,只是认为任何类型的活动都可以作为选项卡激活的充分指标?

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?

推荐答案

只是一个猜测,因为我还没有所有可用于测试的相关浏览器.

Just a guess because I haven't all relevant browsers available for testing.

window 上使用 focus 事件该怎么办.每当用户单击某处时,都会调用该选项,但也会切换选项卡.要区分用户在页面上的操作和用户切换到页面上的行为,您可以检查事件的 explicitOriginalTarget 是否指向 window .

What about using the focus event on the window. 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's explicitOriginalTarget points to the window.

window.onfocus=function(event){
    if(event.explicitOriginalTarget===window){
        console.log('switched from tab');
    }
}

这篇关于检测JavaScript中的标签页/窗口激活的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆