Push event of service worker is not being called

4.6k views Asked by At

I am trying to receive push messages from GCM. I simply followed the tutorial and registered the service worker as below:-

      function urlB64ToUint8Array(base64String) {
      const padding = '='.repeat((4 - base64String.length % 4) % 4);
      const base64 = (base64String + padding)
        .replace(/\-/g, '+')
        .replace(/_/g, '/');

      const rawData = window.atob(base64);
      const outputArray = new Uint8Array(rawData.length);

      for (let i = 0; i < rawData.length; ++i) {
        outputArray[i] = rawData.charCodeAt(i);
      }
      return outputArray;
    }
    var subscribeForPush = function() {
        navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
            serviceWorkerRegistration.pushManager.subscribe({
                    userVisibleOnly: true,
                    applicationServerKey : urlB64ToUint8Array('<API-KEY>')
                })
                .then(function(subscription) {
                    console.log("Subscription for Push successful: ", subscription);
                })
                .catch(function(error) {
                    console.log("Subscription for Push failed", error);
                });
        });
    };
    if ('serviceWorker' in navigator) {
          window.addEventListener('load', function() {
            navigator.serviceWorker.register('/sw.js').then(function(registration) {
              // Registration was successful
              console.log('ServiceWorker registration successful with scope: ', registration.scope);
              subscribeForPush();
            }).catch(function(err) {
              // registration failed :(
              console.log('ServiceWorker registration failed: ', err);
            });
        });
    }

Now, I get the device Id ("cw4jK8NhJgY:APA91bHr64E_kSdh7kN_VjcZRKulPf8KPLJLBjtnHI2qkYzx3-I9aUhunjzVcJjLtkHl9zvN8ys80gADK8tV8SueLX1R2jS0xgrf1Ur6cDw3jNjloUJp8PtWaIN-cEKXj69TZ9-D2Hiw")

from url:- "https://android.googleapis.com/gcm/send/cw4jK8NhJgY:APA91bHr64E_kSdh7kN_VjcZRKulPf8KPLJLBjtnHI2qkYzx3-I9aUhunjzVcJjLtkHl9zvN8ys80gADK8tV8SueLX1R2jS0xgrf1Ur6cDw3jNjloUJp8PtWaIN-cEKXj69TZ9-D2Hiw"

In my service worker file, I simply listen to push messages like:-

     self.addEventListener('push', function(event) {  
          console.log(event)
      });

I am able to send messages to gcm using terminal and get the message:-

   {"multicast_id":4983340130324592129,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1483043226210433%cc9b4facf9fd7ecd"}]}

But I dont know why I dont see logs in push listener? I am stuck in this issue for more than 2 days. Can anyone please help me here? I am doing this in localhost.

4

There are 4 answers

0
bvakiti On

You are not returning the pushManager subscribe

navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
    return serviceWorkerRegistration.pushManager.subscribe({
        'userVisibleOnly': true
}).then(function(subscription) {
        if (!subscription) {
            // Set appropriate app states.
            return;
        }
        console.log(subscription.endpoint);

    }).catch(function (err) {
        console.log('error in subcription .. '+ err);
    });

})

Check my github project https://github.com/bvakiti/bvakiti.github.io/blob/master/app.js

Let me know if you need any details

0
Vik On

I was facing the same issue. I updated my Google Chrome version and it fixed the issue.

0
oninross On

I would like to add to bvakiti's solution by declaring

applicationServerKey: convertedVapidKey

in the pushManager subscribe. Most of the tutorials I found in the internet just uses bvakiti's method and most of the devs who follow that tutorial encountered issues in receiving the push notifications.

0
Khalid Ibrahim On

If you are sure your service worker is registered in the browser but your 'push' event is not getting triggered, you can debug all incoming push notifications to Google Chrome by doing the following:

  1. Open chrome://gcm-internals
  2. Start recording
  3. Send a test push notification to the browser
  4. Observe the logs

The server was getting a 201 on the push request and the browser threw no errors in the console log. However, I was having a decryption issue. The browser was receiving the push notification but failed to decrypt it: AES-GCM decryption failed.

Helpful Source: https://developers.google.com/web/fundamentals/push-notifications/common-issues-and-reporting-bugs