Skip to main content

Push notifications in Web Apps via Service Workers

A push notification is a message that is “pushed” from backend server or application to user interface, e.g. (But not limited to) mobile applications and desktop applications.
Service workers are a great way to run some script in the background and not putting the load on your main business logic running on front-end.
 Your app does not have to be open in the browser, to get the notification. It mean that’s the real purpose of push notifications, notify the user about the content of your application.
                         Application 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.

Register 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

Popular posts from this blog

Design Tools to Help You Create Your Next Project- Part 3

Coolors Coolors   is a super fast color scheme generator. You can explore thousands of pre-existing color schemes (each one features five colors). Or, you can generate your own in a matter of minutes. Once you go to the “generate” page, hit the space bar to start with a different color scheme, and then you can adjust each color’s hue, saturation, and brightness accordingly. Web Gradients Web Gradients   is a collection of almost 200 background gradients, created by the  itmeo  team. You can use each of these content backdrops for any part of your website. You’ll find a .PNG version of each gradient, as well as easy-to-copy CSS3 crossbrowser code. Bonus: there are even curated packs for  Sketch  &  Photoshop . Color Hunt On  Color Hunt , browse through countless palettes, comprised of four colors each. You can browse and sort through the list based on what’s hot and popular, or just pick “random” and see what comes u...

WordPress 4.8 Release Candidate 2 on June 1, 2017

The second release candidate for WordPress 4.8 is now available. To test WordPress 4.8, you can use the  WordPress Beta Tester  plugin or you can  download the release candidate here  (zip). We’ve made  a handful of changes  since releasing RC 1 last week. For more details about what’s new in version 4.8, check out the  Beta 1 ,  Beta 2 , and  RC1  blog posts. Think you’ve found a bug?  Please post to the  Alpha/Beta support forum . If any known issues come up, you’ll be able to  find them here . Happy testing!                                                                                                                   ...

Node.js + MySQL Example: Handling 100's of GigaBytes of Data

Through this Node.js & MySQL example project, we will take a look at how you can efficiently handle  billions of rows  that take up  hundreds of gigabytes  of storage space.                          Secondary goal with this article is to help you decide if Node.js + MySQL is a good fit for your needs, and to provide help with implementing such a solution. The actual code we will use throughout this blogpost  can be found on GitHub . Why Node.js and MySQL? Use MySQL to store the distributed tracing data of the users of our  Node.js Monitoring & Debugging Tool  called Trace. We chose MySQL, because at the time of the decision, Postgres was not really good at updating rows, while for us, updating immutable data would have been unreasonably complex. Most think if anyone has millions/billions of rows, they should use a NoSQL solution such as Cassandra or Mongo. Unfortun...