代码之家  ›  专栏  ›  技术社区  ›  Mathias26

Javascript服务工作者通知超时

  •  3
  • Mathias26  · 技术社区  · 7 年前

    这是我第一次使用serviceworkers和notifications。

    我正在尝试在指定时间显示通知。我试着在服务人员中这样做,如下所示:

    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 回复  |  直到 7 年前
        1
  •  3
  •   Philippe Sultan    7 年前

    在我的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);
      });
    }
    

    使命感 showNotification 在软件工作中,我也尝试了以下代码以及 Applications -> Service Workers -> Push 在Chrome Devtools控制台按钮中,发送推送通知,然后在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);    
    });
    

    希望这有帮助!