Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Push Notifications on the Open Web

If you ask a room of developers what mobile device features are missing from the web, Push notifications are always high on the list.

Push notifications allow your users to opt-in to timely updates from sites they love and allow you to effectively re-engage them with customized, engaging content.

As of Chrome version 42, the Push API and Notification API are available to developers.

The Push API in Chrome relies on a few different pieces of technology, including Web App Manifests and Service Workers. In this post we’ll look at each of these technologies, but only the bare minimum to get push messaging up and running

Implementing Push Messaging for Chrome

This section describes each step you need to complete in order to support push messaging in your web app.

Register a Service Worker

There is a dependency of having a service worker to implement push messages for the web. The reason for this is that when a push message is received, the browser can start up a service worker, which runs in the background without a page being open, and dispatch an event so that you can decide how to handle that push message.

Below is an example of how you register a service worker in your web app. When the registration has completed successfully we call initialiseState(), which we’ll cover shortly.

var isPushEnabled = false;



window.addEventListener('load', function() {
var pushButton = document.querySelector('.js-push-button');
pushButton.addEventListener('click', function() {
if (isPushEnabled) {
unsubscribe();
} else {
subscribe();
}
});

// Check that service workers are supported, if so, progressively
// enhance and add push messaging support, otherwise continue without it.
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
.then(initialiseState);
} else {
console.warn('Service workers aren\'t supported in this browser.');
}
});

The button click handler subscribes or unsubscribes the user to push messages. isPushEnabled is a global variable which simply tracks whether push messaging is currently subscribed or not. These will be referenced throughout the code snippets.

We then check that service workers are supported before registering the service-worker.js file which has the logic for handling a push message. Here we are simply telling the browser that this JavaScript file is the service worker for our site.

Set Up the Initial State


Once the service worker is registered, we need to set up our UI’s state.

Users will expect a simple UI to enable or disable push messages for your site, and they’ll expect it to keep up to date with any changes that occur. In other words, if they enable push messages for your site, leave and come back a week later, your UI should highlight that push messages are already enabled.

You can find some UX guidelines in this doc, in this article we’ll be focusing on the technical aspects.

At this point you may be thinking there are only two states to deal with, enabled or disabled. There are however some other states surrounding notifications which you need to take into account.


There are a number of APIs we need to check before we enable our button, and if everything is supported, we can enable our UI and set the initial state to indicate whether push messaging is subscribed or not.

Since the majority of these checks result in our UI being disabled, you should set the initial state to disabled. This also avoids any confusion should there be an issue with your page’s JavaScript, for example the JS file can’t be downloaded or the user has disabled JavaScript.

<button class="js-push-button" disabled>
Enable Push Messages
</button>

With this initial state, we can perform the checks outlined above in the initialiseState() method, i.e. after our service worker is registered.

// Once the service worker is registered set the initial state  
function initialiseState() {
// Are Notifications supported in the service worker?
if (!('showNotification' in ServiceWorkerRegistration.prototype)) {
console.warn('Notifications aren\'t supported.');
return;
}

// Check the current Notification permission.
// If its denied, it's a permanent block until the
// user changes the permission
if (Notification.permission === 'denied') {
console.warn('The user has blocked notifications.');
return;
}

// Check if push messaging is supported
if (!('PushManager' in window)) {
console.warn('Push messaging isn\'t supported.');
return;
}

// We need the service worker registration to check for a subscription
navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
// Do we already have a push message subscription?
serviceWorkerRegistration.pushManager.getSubscription()
.then(function(subscription) {
// Enable any UI which subscribes / unsubscribes from
// push messages.
var pushButton = document.querySelector('.js-push-button');
pushButton.disabled = false;

if (!subscription) {
// We aren't subscribed to push, so set UI
// to allow the user to enable push
return;
}

// Keep your server in sync with the latest subscriptionId
sendSubscriptionToServer(subscription);

// Set your UI to show they have subscribed for
// push messages
pushButton.textContent = 'Disable Push Messages';
isPushEnabled = true;
})
.catch(function(err) {
console.warn('Error during getSubscription()', err);
});
});
}

A brief overview of these steps:
  • We check that showNotification is available in the ServiceWorkerRegistration prototype. Without it we won’t be able to show a notification from our service worker when a push message is received.
  • We check what the current Notification.permission is to ensure it’s not “denied”. A denied permission means that you can’t show notifications until the user manually changes the permission in the browser.
  • To check if push messaging is supported we check that PushManager is available in the window object. Finally, we used pushManager.getSubscription() to check whether we already have a subscription or not. 
  • If we do, we send the subscription details to our server to ensure we have the right information and set our UI to indicate that push messaging is already enabled or not. We’ll look at what details exist in the subscription object later in this article. 
We wait until navigator.serviceWorker.ready is resolved to check for a subscription and to enable the push button because it’s only after the service worker is active that you can actually subscribe to push messages. 

The next step is to handle when the user wants to enable push messages, but before we can do this, we need to set up a Google Developer Console project and add some parameters to our manifest to use Google Cloud Messaging (GCM). 

Make a Project on the Google Developer Console 

Chrome uses GCM to handle the sending and delivery of push messages, however, to use the GCM API, you need to set up a project on the Google Developer Console. 

The following steps are specific to Chrome because of its use of GCM. We’ll discuss how this would work in other browsers later on in the article. Create a new Google Developer Project To start off with you need to create a new project on https://console.developers.google.com by clicking on the ‘Create Project’ button on the top right.


This post first appeared on Java4you - Java Programming Tutorials, Examples,, please read the originial post: here

Share the post

Push Notifications on the Open Web

×

Subscribe to Java4you - Java Programming Tutorials, Examples,

Get updates delivered right to your inbox!

Thank you for your subscription

×