Push Notifications For the Web

A while ago I built a fun side project on Github to keep a collection of typography links and tools that caught my eye. There are a number of people that follow the project on Github, but every time I make a change or add a new link, I normally update anyone that is interested via social media.

deanhume.github.io/typography – Push Notifications

The problem is that people who are interested in the project may not necessarily follow me on Github or social media and miss out on the updates. Fortunately, the good news is that since the release of Chrome 42, we have had the ability to send notification updates to users in the browser. It’s a great way to keep users updated and notified even when they aren’t browsing of your site. Push Notification API to the rescue!

Notification Message

In order to begin using the Push Notification API in Chrome, there are three parts to the equation. Firstly, you need a Service Worker that will subscribe a user and receive notification messages, then you need to create a project using Google’s Cloud Messaging (GCM) to send the notification messages, and finally you need a web app manifest file in order to link GCM and Chrome.

In this article I am going to run through a basic example and show you how you can send Push Notifications to users on your website using Chrome’s Push Notification API.

REGISTERING THE SERVICE WORKER
Don’t worry if you have never used Service Workers before, the example we are going to run through is simple enough to follow along with no previous experience. However, if you’d like a brief introduction, I recommend reading the following article on HTML5 Rocks which covers the basics of Service Workers.

In order to get started, you will need to create a JavaScript file that we’ll use as our Service Worker. I’ve rather originally called mine ‘service-worker.js’. Next, we need to register the Service Worker and subscribe the user to push messaging with the following code.

if (‘serviceWorker’ in navigator) {
navigator.serviceWorker.register(‘service-worker.js’).then(function(registration) {
// Registration was successful
console.log(‘ServiceWorker registration successful with scope: ‘, registration.scope);
registration.pushManager.subscribe().then(function(subscription){
isPushEnabled = true;
console.log(“subscription.subscriptionId: “, subscription.subscriptionId);
console.log(“subscription.endpoint: “, subscription.endpoint);

// TODO: Send the subscription subscription.endpoint
// to your server and save it to send a push message
// at a later date
return sendSubscriptionToServer(subscription);
});
}).catch(function(err) {
// registration failed 🙁
console.log(‘ServiceWorker registration failed: ‘, err);
});
}
view rawservice-worker.js hosted with ❤ by GitHub

In the code above, we are doing a simple check to see if the browser supports Service Workers, and if so, we then register and install it. Once we have successfully installed the Service Worker, we then need to subscribe to Push Notifications. To subscribe, we have to call the subscribe() method on the PushManager object, which you access through the ServiceWorkerRegistration object.

You may notice that there in the code above, there is a piece of code marked “TODO”. This is because in order to know which users to send messages to, we need to keep track of their unique subscription ID. The unique ID is available on the subscription object. This functionality isn’t automatically handled for you and you will need to keep track of this server side. Then, when you send out a message to all subscribed users, you use the unique subscriptions IDs accordingly. I won’t cover the server side implementation of this, as it will be unique to your stack, but generally it should involve a POST request with the subscription ID. We will use this subscription ID to send a test message later on in this example.

GOOGLE CLOUD MESSAGING
Now that we have registered the Service Worker and created the code to subscribe to Push Messages, we need to create the service to send messages to the client front end. Google’s Cloud Messaging is a great way to handle the sending and delivery of push messages. It is really easy to set up and you can get a project up and running in no time. Head over to console.developers.google.com and create a new project. Once you have created your project, you need to enable the Cloud Messaging service. In the menu, navigate to APIs & Auth, and then select APIs.

Push Notifications Auth

Next, select Cloud Messaging for Android and enable the service.

Google Cloud Messaging

Before we start sending messages, we need to enable access to the API. In the menu, navigate to APIs & Auth, and then select Credentials. Next, create a new Public API access key.

Push Notifications Credentials

Choose Browser Key and ignore the whitelisted IPs unless you specifically want to restrict this to certain IP Addresses. You will need to copy the API key that you have just created as we are going to use it in our manifest file.

Finally, we’ll need to grab the Project ID so that we can link Chrome and Google Cloud Messaging. Using the menu, navigate to Overview and copy the Project ID.

Google Cloud Messaging Project ID

We are going to use this Project ID in the next step.

CREATING A MANIFEST FILE
Now that we have our Project ID, we need to create a manifest file in order to link Chrome to Google Cloud Messaging. A manifest file is a simple JSON file that contains the configuration and settings for the Push Notifications. The code below gives you a basic idea of what a manifest file might look like.

{
“name”: “Push Demo”,
“short_name”: “Push Demo”,
“icons”: [{
“src”: “https://raw.githubusercontent.com/deanhume/typography/gh-pages/icons/typography.png”,
“sizes”: “192×192”,
“type”: “image/png”
}],
“start_url”: “/index.html”,
“display”: “standalone”,
“gcm_sender_id”: “57874135625436178”,
“gcm_user_visible_only”: true,
“permissions”: [
“gcm”
]
}
view rawmanifest.json hosted with ❤ by GitHub
In the manifest file above, you’ll need to swap out the gcm_sender_id with the Project ID that we copied from the Google Developer Console in the previous step. Next, we need to reference the manifest file in your HTML with the following tag in the HEAD of your page.

I’ve called mine manifest.json, but you can name yours however you prefer, as long as you reference it in your HTML.

RESPONDING TO MESSAGES
So far we’ve registered the Service Worker, subscribed the user to push messaging, created a project to send push messages, and created a manifest file to link Chrome to GCM. All that we need to do next, is handle any incoming push messages in our Service Worker.

The following code listens to any incoming push events from the server.

self.addEventListener(‘push’, function(event) {
debugger;
console.log(‘Received a push message’, event);

var title = ‘Notification’;
var body = ‘There is newly updated content available on the site. Click to see more.’;
var icon = ‘https://raw.githubusercontent.com/deanhume/typography/gh-pages/icons/typography.png’;
var tag = ‘simple-push-demo-notification-tag’;

event.waitUntil(
self.registration.showNotification(title, {
body: body,
icon: icon,
tag: tag
})
);
});
view rawservice-worker-push.js hosted with ❤ by GitHub
In order to give the notification message a bit of context, I’ve added an icon and a body message to the notification. Once we’ve sent a notification to the user, we can then decide if we want to redirect them to our site when they click the message. The code below listens to a notification click event and redirects the user to the website.

self.addEventListener(‘notificationclick’, function(event) {
console.log(‘On notification click: ‘, event.notification.tag);
// Android doesn’t close the notification when you click on it
// See: http://crbug.com/463146
event.notification.close();

// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(
clients.matchAll({
type: “window”
})
.then(function(clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url == ‘/’ && ‘focus’ in client)
return client.focus();
}
if (clients.openWindow) {
return clients.openWindow(‘https://deanhume.github.io/typography’);
}
})
);
});
view rawservice-worker-notification.js hosted with ❤ by GitHub

That’s it! Your site is now ready to receive push notifications. Before we start testing this functionality, let’s take a step backwards and put everything together. We started off by registering the Service Worker in the service-worker.js file. We then subscribed the user to push messaging and created a project using Google Cloud Messaging to send the push messages. We then created a manifest file to link Chrome to the GCM project. Finally, we added code to handle incoming notification messages and respond accordingly when they are clicked.

HTTPS BY DEFAULT
It is worth noting that Service Workers require secure origins to ensure that the script is from the intended origin and hasn’t come about from a man-in-the-middle attack. This means that you will need to use HTTPS on live site, although you can use localhost during development.

Push Notifications

If you are looking for a quick way to test this in a live environment, I recommend setting up Github Pages and hosting your project on Github. It comes with a default SSL certificate and allows you to simply navigate to your project URL using HTTPS.

SENDING TEST MESSAGES
There are a number of ways that you can send messages from the cloud using Google’s Cloud Messaging. In order to fire off a message, you need to send a POST request and include the API key and unique subscription IDs from each user. The GCM page has a list of guides and walkthroughs to get you started.

If you are looking to send a quick test email and verify that your code is working, I recommend using a simple cURL message. If you’ve never used cURL before, it is an open source command line tool and library for transferring data easily and quickly. Regardless of whether you are on Windows or Mac, you can download for free it over at curl.haxx.se.

In order to send a simple test message using cURL, use the following syntax.

curl –header “Authorization: key=” –header “Content-Type:application/json” https://android.googleapis.com/gcm/send -d “{\”registration_ids\”:[\”\”]}” –insecure

Once, that is fired off successfully, you should notice a notification message appear in your browser.

Notification Message

Taadaaa! You are now sending push messages using the Notification API.

Reference: deanhume.com

We will be happy to hear your thoughts

      Leave a Comment

      Web Training Guides
      Compare items
      • Total (0)
      Compare
      0