重新加载页面后 Service Worker 显示为已删除

Kan*_*n T 5 javascript push-notification reactjs service-worker progressive-web-apps

正在使用 react 并尝试实现 Service Worker,我编写了一个用于推送通知的迷你 Service Worker 文件,当用户单击按钮时正在注册 Service Worker,现在如果我发送推送消息,它会按预期工作,但是当我重新加载时注册成功后,申请中的service worker页面显示为已删除,请参考截图

服务工作者代码

    const self = this;

    function receivePushNotification(event) {
      console.log('[Service Worker] Push Received.');
      console.log(event);

      // const { image, tag, url, title, text } = event.data.json();

      const options = {
        data: '/neworders',
        body: 'New order request',
        vibrate: [200, 100, 200],
        badge: 'https://spyna.it/icons/favicon.ico',
        actions: [
          {
            action: 'Detail',
            title: 'View',
            icon: 'https://via.placeholder.com/128/ff0000',
          },
        ],
      };
      event.waitUntil(self.registration.showNotification('Hello', options));
    }

    function openPushNotification(event) {
      console.log(
        '[Service Worker] Notification click Received.',
        event.notification.data
      );

      event.notification.close();
      event.waitUntil(clients.openWindow(event.notification.data));
    }

    self.addEventListener('install', function (event) {
      console.log({ event });
      // The promise that skipWaiting() returns can be safely ignored.
      self.skipWaiting();

      // Perform any other actions required for your
      // service worker to install, potentially inside
      // of event.waitUntil();
    });

    self.addEventListener('activate', (event) => {
      console.log('V1 now ready to handle fetches!');
    });
    self.addEventListener('push', receivePushNotification);
    self.addEventListener('notificationclick', openPushNotification);
Run Code Online (Sandbox Code Playgroud)

注册服务工作者函数

function registerServiceWorker() {
  return navigator.serviceWorker.register('/newsw.js');
}
Run Code Online (Sandbox Code Playgroud)

Service Worker 删除的截图

Service Worker 删除的截图

heo*_*khe 1

我怀疑发生这种情况是因为您打开了“重新加载时更新”。

这会强制 Service Worker 在您重新加载页面时进行更新。(在这里阅读更多)

  • 请编辑您的答案并写下您提供的链接内容的简短摘要。请记住,此类内容以后可能不再可用。阅读[答案]。 (2认同)