pplication server tells Google Cloud Messaging (GCM) server that there is something new content and GCM server then awakens the service worker which generates the push notification.
Here is what did in above snippet of code:
1. Checking if the browser supports service worker and push notifications.
2. Handle accordingly if the browser doesn’t support them.
3. If they do, register the service worker file and get the registration object.
Note: user Visible Only: true must be true, otherwise you will get an error in your browser console.
ARegister Service Worker
if ('serviceWorker' in navigator && 'PushManager' in window) {
navigator.serviceWorker.register('software-worker.js')
.then(function(reg) {
registration = reg;
})
.catch(function(error) {
return;
});
} else {
// Well Service Worker or Push Notifications
// aren't supported
// yet in your browser
}
Here is what did in above snippet of code:
1. Checking if the browser supports service worker and push notifications.
2. Handle accordingly if the browser doesn’t support them.
3. If they do, register the service worker file and get the registration object.
Subscribe to Notifications from client
registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: UInt8array Key
})
.then(function(subscription) {
if (subscription) {
// User is already subscribed
}
})
.catch(function(err) {
// User have declined request for Push notifications
});
This is what doing above:
1. Using push manager service create the subscription.
2. You need to have application Server Key for this.
3. Once got the subscription object, send it to server.
Note: user Visible Only: true must be true, otherwise you will get an error in your browser console.
Push notifications handler
self.addEventListener('push', function(event) {
event.waitUntil(
self.registration.showNotification(Title, {
body: Body,
icon: Icon
})
);
});
It will trigger every time, your service worker will be awakened by GCM server.
And that’s it, you have an active service worker that will push notifications to the user every time GCM server will call it.
This post’s scope was only to cover the use of service workers in push notifications
Comments
Post a Comment