JavaScript 服务工作者通知超时问题

4

这是我第一次与Service Workers和通知有关的技术打交道。

我正在尝试在指定时间显示一个通知。我尝试在Service Worker中执行以下操作:

function showNotification() {
    setTimeout(function () {
        self.registration.showNotification('Title', {
            body: 'body blablabla',
            badge: 'assets/images/logo.jpeg',
            icon: 'assets/images/logo.jpeg',
            renotify: false,
            requireInteraction: true,
            silent: false,
            vibrate: [200, 100, 200],
            dir: 'ltr',
            lang: 'en-US'
        });
    }, 3000);

}

我尝试过,但没有收到任何通知。当我删除setTimeout函数后,就会收到通知,所以我认为这与超时有关。是否还有其他方法,或者我遗漏了什么?谢谢!
1个回答

4

在我的Chrome JavaScript函数中调用该函数(不在服务工作者中)实际上在我的情况下可以正常工作,我是这样尝试的:

function showNotification() {
  navigator.serviceWorker.getRegistration().then(registration => {
    setTimeout(() => {
        registration.showNotification('Title', {
            body: 'body blablabla',
            badge: '/images/icon-light.png',
            icon: '/images/icon-light.png',
            renotify: false,
            requireInteraction: true,
            silent: false,
            vibrate: [200, 100, 200],
            dir: 'ltr',
            lang: 'en-US'
        });
    }, 3000);
  });
}

从 Service Worker 中调用 showNotification 也是可以的,我刚刚尝试了以下代码,并结合 Chrome 开发者工具中的 Applications -> Service Workers -> Push 按钮来发送推送通知,然后在 3 秒后显示它:

self.addEventListener('push', function(event) {
  if (event.data) {
    console.log('This push event has data: ', event.data.text());
  } else {
    console.log('This push event has no data.');
  }

  setTimeout(() => {
    self.registration.showNotification(
      'Title',
      {
        body: 'body blablabla',
        badge: '/images/icon-light.png',
        icon: '/images/icon-light.png',
        renotify: false,
        requireInteraction: true,
        silent: false,
        vibrate: [200, 100, 200],
        dir: 'ltr',
        lang: 'en-US'
      }
    ); 
  }, 3000);    
});

希望这能帮到您!

4
由于浏览器可能会决定杀死服务工作者以节省资源,因此此过程可能无法预测地失败。您需要使用 waitUntil 来确保服务工作者在超时触发之前保持活动状态。即使如此,浏览器也可能会在超时期间内杀死服务工作者。等待时间越长,机会越大。但这是一件好事。想象一下,您曾经访问的每个页面都有一个服务工作者,每个服务工作者都不断触发超时以发送某些分析数据。 - lordvlad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接