PWA。服务工作者通知多次出现

问题描述 投票:1回答:1

我有运行服务工作者的网站。我可以打印它工作得很好的通知,但我只需要显示一次通知。但是每次刷新页面时,每次都会显示相同的消息。是否可以只显示一次通知?有我的代码:

function displayNotification() {
  if (Notification.permission == 'granted') {
    navigator.serviceWorker.getRegistration().then(function(reg) {
      var options = {
        body: 'Welcome!',
        icon: '/css/logo.png',
        vibrate: [100, 50, 100],
        data: {
          dateOfArrival: Date.now(),
          primaryKey: 1
        }
      };
      reg.showNotification('My name', options);
    });
  }
}


navigator.serviceWorker.register('/service-worker.js');
Notification.requestPermission(function(result) {
  if (result === 'granted') {
    navigator.serviceWorker.ready.then(function(registration) {
      displayNotification();
    });
  }
});
javascript html google-chrome progressive-web-apps
1个回答
2
投票

可以在服务工作者执行的上下文中显示通知。当服务工作者通过push event“醒来”时,通常会这样做。

还可以在网页的上下文中显示通知。这样做根本不需要服务工作者。如果您的用例在用户授予通知权限后立即显示单个通知,则可以使用相同的通知和权限API,而不涉及服务工作者。

这是一个说明如何做到这一点的示例。它有点欺骗,因为它不会在第一次访问时签入,而只会在'granted'的通知权限发生变化时显示通知。因为这通常只发生一次而不是每次访问,所以它应该完成同样的事情。

if ('Notification' in window && 'permissions' in navigator) {
  function showNotification() {
    const title = 'The title';
    const options = {
      body: 'The body.',
    };
    new Notification(title, options);
  }

  navigator.permissions.query({name: 'notifications'}).then(status => {
    if (status.state === 'prompt') {
      status.onchange = () => {
        if (status.state === 'granted') {
          showNotification();
        }
      };

      document.querySelector('#notification')
        .addEventListener('click', () => Notification.requestPermission());
    }
  });  
}
<button id="notification">Enable Notification</button>
© www.soinside.com 2019 - 2024. All rights reserved.