簡體   English   中英

JavaScript服務工作者通知超時

[英]Javascript service worker notification timeout

這是我第一次與服務人員和通知一起工作。

我正在嘗試在指定時間顯示通知。 我嘗試在服務工作者中這樣做,如下所示:

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函數時,會收到一條通知,因此我認為它與超時有關。 還有其他方法還是我錯過了什么?

謝謝!

在我的情況下,實際上可以在我的Chrome JavaScript函數中(在Service Worker之外)調用該函數,我嘗試通過以下方式進行嘗試:

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

從SW調用showNotification也可以,我只是在Chrome Devtools控制台按鈕中嘗試了以下代碼以及Applications -> Service Workers -> Push Workers- Applications -> Service Workers -> Push來發送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);    
});

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM