简体   繁体   English

Javascript。 检查是否没有焦点标签

[英]Javascript. Check if there is no tab in focus

Now i'm using visibilitychange event to see which browser tab is active. 现在,我正在使用可视性更改事件来查看哪个浏览器选项卡处于活动状态。 I use active tab to watch some events on server side, and I don't want to run this watcher in all open tabs. 我使用活动选项卡来监视服务器端的某些事件,并且我不想在所有打开的选项卡中运行此监视程序。

But now I want to run this watcher even if no tab is in focus, but still, in just one tab. 但是,即使没有选项卡聚焦,但现在我仍要运行此观察程序,但仍然只有一个选项卡。

How to check if no tab is in focus and ensure that some script is running in only one background tab? 如何检查是否没有标签集中,并确保某些脚本仅在一个后台标签中运行?

You have to solve the issue of communicating between tabs. 您必须解决选项卡之间进行通信的问题。 There are several options: 有几种选择:

  1. Cookies 饼干
  2. Local storage 本地存储
  3. Server side syncing (WebSockets, Ajax pooling, etc) 服务器端同步(WebSocket,Ajax池等)

Each tab will have to update its state in the shared data centre (one of the above). 每个选项卡都必须在共享数据中心(上述之一)中更新其状态。

Once that is done, you should use a master selecting algorithm to decide which one of the tab should communicate with the server. 完成后,您应该使用主选择算法来确定哪个选项卡应与服务器通信。 In your case, this could be as simple as the first opened tab. 就您而言,这可能与第一个打开的选项卡一样简单。

There are some quirks when using local storage such as two different sub-domains can't access the same local storage. 使用本地存储时会有一些怪癖,例如两个不同的子域无法访问同一本地存储。 Cookies are another way around where you can define parent domain as well. Cookies是您可以在其中定义父域的另一种方法。 I would say the third option is the best in terms of debugging and adding more complex selection logic. 我想说第三个选项是调试和添加更复杂的选择逻辑方面的最佳选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM