【问题标题】:How to check if Chrome window is focused?如何检查 Chrome 窗口是否聚焦?
【发布时间】:2020-02-05 18:11:49
【问题描述】:

我正在使用带有服务工作人员的 Push API 开发通知。我目前正在做这样的事情,以便仅在用户尚未进入网站时才显示通知:

self.addEventListener('push', function(event) {
  event.waitUntil(clients.matchAll().then(function(clientList) {
    for (let i = 0; i < clientList.length; i++) {
      if (clientList[i].visibilityState === "visible") { // if any window is visible, don't send a notification
        return;
      }
    }

    event.waitUntil(self.registration.showNotification("Notification"));
  })
}

这没问题,除了如果用户通过标签进入我的网站,但从浏览器中退出,则它不起作用。我会做一张桌子:

user is tabbed into site                            notification not sent    CORRECT
user is not tabbed into site                        notification is sent     CORRECT
user is not tabbed into site or browser             notification is sent     CORRECT
user is tabbed into site but tabbed out of browser  notification not sent    INCORRECT

是否有可能解决最后一种情况?我希望在这种情况下发送通知。

【问题讨论】:

    标签: javascript google-chrome push-notification service-worker


    【解决方案1】:

    visibilitychange 活动适合您吗?

    您可以将其添加到您的纯 javascript 文件中,然后在可见性发生变化时向 service worker 发送消息

    <script type="text/javascript">
        document.addEventListener("visibilitychange", function() {
            if (document.visibilityState === 'visible') {
                console.log('IS VISIBLE');
            } else {
                console.log('NOT VISIBLE');
                let meg = {...some message object}
                swRegistration.active.postMessage(msg);
            }
        });
    
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-30
      • 1970-01-01
      相关资源
      最近更新 更多