如何检测浏览器窗口是否关注?

时间:2023-01-23 07:17:12

My page should make notification sounds only when the window is in the background. I can track the window.onfocus and window.onblur events to notice when the focus state changes. However, I don't know whether the window will load focused or not, since it might load in a background tab, for instance.

只有当窗口在后台时,我的页面才会发出通知声音。我可以跟踪window.onfocus和window.onblur事件,以便注意焦点状态何时发生变化。但是,我不知道窗口是否会加载焦点,因为它可能会加载到背景选项卡中。

How do I decide whether to play sounds or not before I get an onfocus/onblur event?

在获得onfocus / onblur事件之前,如何决定是否播放声音?

2 个解决方案

#1


Couldn't you just assume it's loaded blurred, and then change the status to focused as soon as you receive any type of event (keydown/mousemove)?

难道你不能假设它被加载模糊,然后一旦你收到任何类型的事件(keydown / mousemove)就将状态改为焦点?

#2


The onfocus event should be triggered when the page is initially opened (in the foreground). At least it is in FF3/IE8.

最初打开页面时(前景中)应触发onfocus事件。至少它在FF3 / IE8中。

So you could have sounds on initially, turn them off when onfocus is triggered, and turn them back on when onblur is triggered.

因此,您可以在最初发出声音,在触发onfocus时将其关闭,并在触发onb​​lur时将其重新打开。

#1


Couldn't you just assume it's loaded blurred, and then change the status to focused as soon as you receive any type of event (keydown/mousemove)?

难道你不能假设它被加载模糊,然后一旦你收到任何类型的事件(keydown / mousemove)就将状态改为焦点?

#2


The onfocus event should be triggered when the page is initially opened (in the foreground). At least it is in FF3/IE8.

最初打开页面时(前景中)应触发onfocus事件。至少它在FF3 / IE8中。

So you could have sounds on initially, turn them off when onfocus is triggered, and turn them back on when onblur is triggered.

因此,您可以在最初发出声音,在触发onfocus时将其关闭,并在触发onb​​lur时将其重新打开。