检查Service Worker中的窗口是否处于活动状态 [英] Check if window is active from Service Worker

查看:127
本文介绍了检查Service Worker中的窗口是否处于活动状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to run a Web Application that sends push notifications when the window is inactive. To do this, I have a Service Worker that helps receives notifications from my php server (through Firebase).

但是,我不确定如何通过我的服务工作人员检查窗口是否处于活动状态。服务工作者无法访问DOM,因此我无法直接通过那里检查它,并且我已经尝试对附加的JS文件进行检查,但服务工作者获得的变量没有定义错误。我的服务工作者代码如下:

However, I'm unsure how to check if the window is active through my Service worker. The Service Worker does not have access to the DOM, so I can't check it directly through there, and I've tried doing the checks on an attached JS file, but the Service Worker gets variable not defined errors. My Service Worker code is as follows:

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')
  );
});

任何人都可以通过正确的方式来启发我检查活动窗口以阻止推送通知应用程序是否处于活动状态?

Could anyone enlighten me on the proper way to check for an active window to prevent push notifications if the web app is active?

谢谢!

推荐答案

您可以使用visibility API - >
https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API?redirectlocale=en-US&redirectslug=DOM%2FUsing_the_Page_Visibility_API

You can use the visibility API -> https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API?redirectlocale=en-US&redirectslug=DOM%2FUsing_the_Page_Visibility_API

在主页面上附加一个事件监听器以与您的服务工作者交谈。然后服务工作者可以相应地执行。

Attach an event listener on the main page to talk to your service worker. Then the service worker can execute accordingly.

这篇关于检查Service Worker中的窗口是否处于活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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