javascript – 等待ServiceWorker在订阅之前完成注册

前端之家收集整理的这篇文章主要介绍了javascript – 等待ServiceWorker在订阅之前完成注册前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用ServiceWorker来实现用户通知.当用户首次访问该站点并批准通知时,ServiceWorker将注册订阅
if ('serviceWorker' in navigator) {
 console.log('Service Worker is supported');
 navigator.serviceWorker.register('/js/sw.js').then(function(reg) {
   if(/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())){
       reg.pushManager.subscribe({
           userVisibleOnly: true
       }).then(function(sub) {
           console.log('endpoint:',sub.endpoint);
           endpoint = sub.endpoint;
           fetch(MY_API+encodeURIComponent(endpoint),{
                    credentials: 'include'
                 })
       });
   }
 }).catch(function(err) {
   console.log(':^(',err);
 });
}

在第一次访问时,这涉及:

Uncaught (in promise) DOMException: Subscription Failed - no active Service Worker

从第二次访问开始,一切正常,因为ServiceWorker当时已处于活动状态.看起来这是一个时间问题.在尝试订阅之前,如何确保ServiceWorker已成功注册并处于活动状态?

我尝试使用navigator.serviceWorker.ready,如下所示:

if ('serviceWorker' in navigator) {
 console.log('Service Worker is supported');
 navigator.serviceWorker.register('/js/sw.js').then(function(sreg) {
   console.log(':^)',sreg);
   navigator.serviceWorker.ready.then(function(reg) {
       if(/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())){
           reg.pushManager.subscribe({
               userVisibleOnly: true
           }).then(function(sub) {
               console.log('endpoint:',sub.endpoint);
               endpoint = sub.endpoint;
               fetch("https://www.wettfreun.de/?page=fetch&s=1&endpoint="+encodeURIComponent(endpoint),{credentials: 'include'})
           });
       }
   });
 }).catch(function(err) {
   console.log(':^(',err);
 });
}

现在从不调用navigator.serviceWorker.ready.then()中的部分.

解决方法

你可以使用 ServiceWorkerContainer.ready.

MDN的例子:

function subscribe() {
  var subscribeButton = document.querySelector('.js-subscribe-button');
  subscribeButton.disabled = false;

  navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
    serviceWorkerRegistration.pushManager.subscribe()
      .then(function(subscription) {
        // The subscription was successful
        subscribeButton.disabled = true;
        return sendSubscriptionToServer(subscription);
      })
      .catch(function(error) {
        if (Notification.permission === 'denied') {
          console.log('Permission for Notifications was denied');
          subscribeButton.disabled = true;
        } else {
          console.log('Unable to subscribe to push.',error);
          subscribeButton.disabled = false;
        }
      });
  });
}
原文链接:https://www.f2er.com/js/157796.html

猜你在找的JavaScript相关文章