22

Using Web Notifications to Increase Engagement in PWAs

 5 years ago
source link: https://www.tuicool.com/articles/hit/NJ7JZfq
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Most of the features and APIs we have seen in the mobile world are now available on the web as well. That rich set of web APIs is making Progressive Web Apps (PWAs) a great alternative, if not a replacement, to most mobile app experiences out there. An empowered and rich web makes PWAs the most cost-effective way to engage with your audience when compared to traditional mobile apps. With PWAs you have one single codebase using one single set of APIs that you can continuously deliver and run everywhere.

Engage With Your Audience

An effective way to get users to engage with your PWA is through Web Push Notifications. Once the user has opted-in, Web Push Notifications allow them to receive relevant and customized updates. This helps to bring them back to your PWA; effectively re-engaging with them. Web Push Notifications opens a new set of possibilities and works through a combination of Web APIs:

  • Push API : allows web apps to receive and process messages pushed from a server - even if the web app is not loaded.
  • Notification API : allows web apps to display system notifications to the user - even when the user has moved to another app or switched tabs.

Browser Support

The WHATWG Notification API 1 has been adopted by most modern browsers, the only exception is iOS Safari which doesn’t support it at all. Chrome for Android supports notifications via the Push API but not the Web Notifications API.

vEviieA.png!web

Click through to the original article for interactive graphs.

The W3C Push API 2 is still a working draft but has been adopted by most modern browsers, except for desktop Safari because it has its own custom implementation, and iOS Safari which has no support at all.

BRRjmiv.png!web

Request Permission

To be able to use the Notification API and display system notifications, permission must be requested and granted by the end user. The current permission status can be checked at any point using Notification.permission or requested using  Notification.requestPermission() . The possible results for both are either  granteddenied or  default ; the latter meaning that the permission status is unknown; possibly because it wasn’t asked yet - effectively acting as  denied ,

Check permission status:

const permission = Notification.permission

Requesting permission:

const permission = await Notification.requestPermission()

Though this seems like a fairly straightforward process, only a few API calls, take note! If your user denies the permission to receive notifications, this decision is permanent and you won’t have a second chance to ask for it. So rather than just asking permission as soon as the user lands in your PWA, do it at a more opportune moment, when the user is more open to accepting, for example, when they interact or request something from within your app.

Build a Notification

Once permission has been granted by the user, it is quite simple to build and display a notification. Choose a title, a few other optional properties and click handler, and the notification is displayed immediately.

const notification = new Notification('Sample notification by nearForm', {
  icon: '/img/favicon-96x96.png',
  body: 'This is a sample notification'
  tag: 'foobar' // works as an identifier of this notification
})
notification.onclick = function () {
  window.focus()
  alert('Just got clicked!')
  this.close()
}

Push Notifications With Service Worker

It is possible to send push notifications to the user regardless of the web app being in the foreground or even currently loaded. To achieve this, a service worker must be active and must subscribe to push notifications using PushManager.subscribe() . This function returns both an endpoint and the encryption key needed for the server to push data. After this setup step, the service worker is ready to receive pushed data by listening to a  push event.

Main Client Code

// register service worker
navigator.serviceWorker.register('service-worker.js')
// wait until is ready
const registration = await navigator.serviceWorker.ready
// subscribe to push data
const subscription = await registration.pushManager.subscribe({ ... })
// send `subscription` to the server that will push data
await fetch('register', {
  method: 'post',
  // ...
  body: JSON.stringify({ subscription })
})

Service Worker Code

self.addEventListener('push', event => {
  // data that was pushed by the server
  const data = event.data.json()
  // show notification using an alternative API available for the service worker
  event.waitUntil(self.registration.showNotification(data.title, {
    body: data.body
  })
})

Conclusion

Web Push Notifications is another of many new APIs that is closing the gap between web and mobile development. Unfortunately, Safari is lagging a bit behind on these specific APIs, most likely because it breaks Apple’s mobile app business. It’s ironic that even though Google coined the term, PWAs were actually envisioned by Steve Jobs and first announced back in the 2007 WWDC during one of his “one more thing” moments. The original way to develop apps for the iPhone was based on web technologies and not proprietary SDKs. Apple moved forward by adding support to Web Workers in Safari, let’s hope they keep the pace and help make the web the best platform to build apps.

This is our last post of our series on PWAs, other articles can be found in our blog here:

Links and footnotes:

  1. https://notifications.spec.whatwg.org/  
  2. https://w3c.github.io/push-api/  
  3. https://developer.apple.com/notifications/safari-push-notifications/  

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK