Can't subscribe to Push notification

2019-06-10 03:04发布

问题:

I'm trying to subscribe to PushManager to send push notification, but I'm always getting an error when calling subscribe.

This is my subscribe call

registration.pushManager.subscribe({ userVisibleOnly: true })
  .then(function (subscription) { /* ... */})
  .catch(function (err) { /* ... */})

Nothing weird as you can see, and that call is always throwing

DOMException: Registration failed - push service error

I'm not sure why is that. What I've checked so far

  • I have a gcm_sender_id property in my manifest.json.
  • The permision for notification is granted in the client.
  • registration.pushManager.getSubscription() always get null and subscribe always throw the above error.

What else should I look? Any help to succesfully subscribe to push notifications is welcome, by the way, I'm using chrome 55, if you need more info just let me know.

EDIT: All of the registration code is here on the registerServiceWorker function.

Thanks.

回答1:

Assuming you have registered the service worker properly, using something like :

navigator.serviceWorker.register('/serviceworker.js', {
                scope: '/'
            });

I suggest you use a relative path for your service worker like I did instead of using window.location.origin like you did in your code and it is always better to keep the serviceworker file at the root.

Use this approach to subscribe for push and get an endpoint.

navigator.serviceWorker.ready
            .then(function(serviceWorkerRegistration) {
                return serviceWorkerRegistration.pushManager.subscribe({
                    userVisibleOnly: true
                });
            })
            .then(function(subscription) {console.log(subscription.endpoint);});

If it still doesn't work: -Try unregistering the existing worker from chrome://serviceworker-internals and make sure you close all tabs when you do that.

If it still doesn't work: -Try creating a new chrome profile by clicking on your name in the top right corner of chrome. (I faced this once)

Check this code for your reference.



回答2:

I would like to mention something that happened to me related to DOMException while subscribing the browser/web push user with FCM push service which is, the subscription was working like magic however as I was testing my app I was hitting FCM push service/server a lot. this led to a TOO_MANY_REGISTRATIONS error which can be checked via chrome://gcm-internals. The solution was pretty logical, just create a new profile/user on chrome.

FCM was rejecting any registration request from previous chrome user and I believe FCM was considering it as a SPAM or someone hacking their server. Thanks to @Dhruv Batheja for bringing my attention to that.