小编Oze*_*zer的帖子

从 Service Worker 检查窗口是否处于活动状态

我正在尝试运行一个 Web 应用程序,该应用程序在窗口处于非活动状态时发送推送通知。为此,我有一个 Service Worker,可以帮助从我的 php 服务器(通过 Firebase)接收通知。

但是,我不确定如何通过我的 Service Worker 检查窗口是否处于活动状态。Service Worker 无权访问 DOM,因此我无法直接通过那里检查它,并且我尝试对附加的 JS 文件进行检查,但 Service Worker 收到变量未定义错误。我的 Service Worker 代码如下:

self.addEventListener('push', function(event) {
  console.log('[Service Worker] Push Received.');
  // console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);

  const title = 'Chat';
  const options = {
    body: 'New message received!',
    icon: '/images/logo/8-icon.png',
    badge: '/images/badge.png'
  };

  event.waitUntil(self.registration.showNotification(title, options));

});

self.addEventListener('notificationclick', function(event) {
  console.log('[Service Worker] Notification click Received.');

  event.notification.close();

  event.waitUntil(
    clients.openWindow('https://localhost:8000')
  );
});
Run Code Online (Sandbox Code Playgroud)

如果网络应用程序处于活动状态,任何人都可以启发我检查活动窗口以防止推送通知的正确方法吗?

谢谢!

javascript php dom push-notification service-worker

5
推荐指数
2
解决办法
2700
查看次数

标签 统计

dom ×1

javascript ×1

php ×1

push-notification ×1

service-worker ×1