简体   繁体   English

未捕获(在承诺中)DOMException:订阅失败 - 没有活动的服务工作者

[英]Uncaught (in promise) DOMException: Subscription failed - no active Service Worker

I'm trying to subscribe the user but this is the error I get the first time. 我正在尝试订阅用户,但这是我第一次收到的错误。 The second time, it is working because the user is already active 第二次,它正在工作,因为用户已经处于活动状态

This is my code : 这是我的代码:

 if ('serviceWorker' in navigator) {
   console.log('Service Worker is supported');
   navigator.serviceWorker.register('sw.js').then(function(reg) {
     console.log(':^)', reg);
     reg.pushManager.subscribe({
       userVisibleOnly: true
     }).then(function(sub) {
       console.log('endpoint:', sub.endpoint);
       var div = document.getElementById('id');
       div.innerHTML = div.innerHTML + sub.endpoint;
       // var b = document.getElementsByTagName('body')[0];
       //b.appendChild(div);
       //alert(sub.endpoint);
     });
   });
 }

I already tried the following, but the ready.then() method is not happening: 我已经尝试过以下内容,但是ready.then()方法没有发生:

 if ('serviceWorker' in navigator) {
   console.log('Service Worker is supported');
   navigator.serviceWorker.register('sw.js').then(function(sreg) {
     console.log(':^)', sreg);
     navigator.serviceWorker.ready.then(function(reg) {
       reg.pushManager.subscribe({
         userVisibleOnly: true
       }).then(function(sub) {
         console.log('endpoint:', sub.endpoint);
         var div = document.getElementById('id');
         div.innerHTML = div.innerHTML + sub.endpoint;
         // var b = document.getElementsByTagName('body')[0];
         //b.appendChild(div);
         //alert(sub.endpoint);
       });
     });
   });
 }

Any ideas ? 有任何想法吗 ?

You should wait for the service worker to be activated before triggering the subscription. 您应该在触发订阅之前等待服务工作程序激活。

use stateChange listener for figuring out if service worker is active 使用stateChange侦听器来确定服务工作者是否处于活动状态

navigator.serviceWorker.register(workerFileName, {scope: "/"})
    .then(
    function (reg) {
        var serviceWorker;
        if (reg.installing) {
            serviceWorker = reg.installing;
            // console.log('Service worker installing');
        } else if (reg.waiting) {
            serviceWorker = reg.waiting;
            // console.log('Service worker installed & waiting');
        } else if (reg.active) {
            serviceWorker = reg.active;
            // console.log('Service worker active');
        }

        if (serviceWorker) {
            console.log("sw current state", serviceWorker.state);
            if (serviceWorker.state == "activated") {
                //If push subscription wasnt done yet have to do here
                console.log("sw already activated - Do watever needed here");
            }
            serviceWorker.addEventListener("statechange", function(e) {
                console.log("sw statechange : ", e.target.state);
                if (e.target.state == "activated") {
                    // use pushManger for subscribing here.
                    console.log("Just now activated. now we can subscribe for push notification")
                    subscribeForPushNotification(reg);
                }
            });
        }
    },
    function (err) {
        console.error('unsuccessful registration with ', workerFileName, err);
    }
);

You can resolve this by checking for service worker status. 您可以通过检查服务工作者状态来解决此问题。 Perform your actions only when the service worker is active. 仅在服务工作者处于活动状态时执行操作。

navigator.serviceWorker.register('sw.js').then(function(reg) {
 if(reg.installing) {
        console.log('Service worker installing');
    } else if(reg.waiting) {
        console.log('Service worker installed');
    } else if(reg.active) {
        console.log('Service worker active');
    }
 // Include below mentioned validations
}

Check for pushnotification is supported or not using 支持或不支持检查推送

 // Check if push messaging is supported  
    if (!('PushManager' in window)) {  
       console.log('Push messaging isn\'t supported.');  
       return;  
     }
   //
   if (Notification.permission === 'denied') {  
      console.log('The user has blocked notifications.');  
      return;  
   }

After these two checks implement you functionality. 在这两个检查后实现您的功能。

navigator.serviceWorker.ready.then(function(reg) {  .... })

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法订阅用户:DOMException:订阅失败 - 没有活动的 Service Worker - Failed to subscribe the user: DOMException: Subscription failed - no active Service Worker Service Worker 中抛出错误“Uncaught (in promise) DOMException” - Error "Uncaught (in promise) DOMException" thrown in Service Worker Service Worker - 未捕获(承诺)TypeError:无法获取 - Service Worker - Uncaught (in promise) TypeError: Failed to fetch Uncaught (In Promise) TypeError: Failed to Fetch - In Service worker when offline - Uncaught (In Promise) TypeError: Failed to Fetch - In Service worker when offline Uncaught (in promise) TypeError: Failed to fetch - Service Worker with workbox - Uncaught (in promise) TypeError: Failed to fetch - Service worker with workbox IndexedDB:未捕获(承诺)DOMException - IndexedDB: Uncaught (in promise) DOMException 未捕获的DOMException:无法构造'Worker':位于papaparse.mi.js的脚本 - Uncaught DOMException: Failed to construct 'Worker': Script at papaparse.mi.js Chrome:未捕获(承诺)DOMException:无法加载,因为找不到支持的源 - Chrome: Uncaught (in promise) DOMException: Failed to load because no supported source was found 捕获未捕获(承诺)的DOMException javascript - catching Uncaught (in promise) DOMException javascript 未捕获(承诺)DOMException:超出配额 - Uncaught (in promise) DOMException: Quota exceeded
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM