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")
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.
You are not returning the pushManager subscribe
Check my github project https://github.com/bvakiti/bvakiti.github.io/blob/master/app.js
Let me know if you need any details