What is the difference between `pushManager.subscribe` and` pushManager.getSubscription` Service Worker's

PushManager.getSubscription ()

Retrieves an existing push subscription. It returns a promise that resolves the PushSubscription object containing information about the existing subscription. If an existing subscription does not exist, this eliminates the null value.

[...]

PushManager.subscribe ()

Subscribes to the push service. It returns a promise that resolves the PushSubscription object containing the push subscription information. A new push subscription is created if the current service employee does not have an existing subscription.

According to MDN documentation pushManager . There, the methods are almost identical, except that in the case of getSubcription() it can be resolved with a null value.

I basically understand that I can just use subscribe() , and Service Worker will try to get a subscription if it is available, and also create a new one if it is not available.

=> But I tried to do something else. First I want to try to get a subscription, if it is allowed using null , I will try to subscribe to it.

  navigator.serviceWorker.register('./worker.js') .then(function(reg) { // Subscribe push manager reg.pushManager.getSubscription() .then(function(subscription) { if(subscription){ // TODO... get the enpoint here } else { reg.pushManager.subscribe() .then(function(sub){ // TODO... get the endpoint here }); } }, function(error) { console.error(error); }) }); 

But then I ended up with an error:

Unprepared (in promise) DOMException: subscription failed - no active Service Worker

This is confusing, and I doubt that this is a limitation of Chrome on the Push API working, or may be a mistake. Does anyone have any information about this strange behavior?

+5
source share
1 answer

The problem is that your service worker is registered, but not yet activated.

You can use navigator.serviceWorker.ready instead of subscribing immediately after registering the worker.

If you want to activate a service worker as soon as possible, you can use skipWaiting and Clients.claim , as described in this CookbookWorker recipe .

+6
source

Source: https://habr.com/ru/post/1247188/


All Articles