Push Notifications on the Web - Google Chrome

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.

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.

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.

<link rel="manifest" href="manifest.json">

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.

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.

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.

What's next?

If you'd like to see a live working version of this code, please head over to deanhume.github.io/typography using Chrome to find out more.

As an API, push messaging is relatively new and is constantly improving. While this article covered Chrome, support for Push Notifications is also available in Firefox, Safari, Opera and Android.

For further reading, I recommend checking out the following articles:

HTML5 Rocks - Push Notifications on the Open Web

Google's Cloud Messaging


Luis - 8/6/2015
Interesting article. I'm a little unclear as to where service-worker-push.js and service-worker-notification.js live in the example code. Is self a variable referencing something from the service-worker.js script?

Jagadeesh - 8/7/2015
Interesting info. Thanks much for sharing it.

Me - 8/8/2015
When do I get a notification? Only when i am in your site? How can i unsubscribe? Couldnt find an Option in chrome.

Cristian - 8/13/2015
Interesting article, i'd love to see a screencast where you show how to make this thing from scratch.

Anders - 8/13/2015
Great article but it's stuff like this that breaks the web.

Raymond Camden - 8/13/2015
@Anders: How exactly does this "break" the web? His code will not throw an error in unsupported browsers.

RyderSkerst1 - 8/14/2015
nice Article Responding to messages code are very help full. thank you so much.....

RyderSkerst1 - 8/17/2015
Great article. thank you so much

jpmedley - 8/20/2015
Here's a few Chrome45 updates: (1) subscriptionId was deprecated and its value rolled into the endpoint. (2) gcm_user_visible_only has been deprecated and replaced by passing {userVisibleOnly: true } to the subscribe() function.

shriek - 9/22/2015
Correct me if I'm wrong but doesn't registering `service-worker.js` from within `service-worker.js` cause an infinite loop? I believe that filename should be `main.js` and `service-worker.js` really should be either `service-worker-push.js` or `service-worker-notification.js`. @Luis, From my understanding so far, your `main.js` should contain the code in `service-worker.js` as shown in this article which registers a service worker and service workers really are just a new thread that runs in the background. Your `service-worker-push.js` or `service-worker-notification.js` are the service-worker that you want to register in your `main.js` file which attaches events to which it listens to in the newly created thread(service-worker). Also, it's not really clear from the article what `registration-ids` are in the curl request. They're essentially the `endpoint` that you get in the callback of the service-worker's promise, which is really [this ](https://gist.github.com/deanhume/2f04d6b1b6316fc97c52#file-service-worker-js-L8).

Shahrier Akram - 10/23/2015
If you're looking custom payload in the push notification, this ain't ready and is a huge bummer in my books. So notifications with custom payload need to be persisted somewhere and use that location to retrieve the latest notification, after you receive this 'pre-'notification. http://stackoverflow.com/a/30337242/313200

Pasupathy - 1/6/2016
I am getting this error when i copy and paste the js code to register service-worker.js ServiceWorker registration failed: DOMException: Only secure origins are allowed (see: https://goo.gl/Y0ZkNV).

jpmedley - 1/11/2016
@Pasupathy Service workers can only be served over HTTPS.

jeetendra - 3/29/2016
i done all on locahost but how to test it ,curl thing not clear to ,the last step

Nikhil Sheth - 5/4/2016
How to send --- custom msg --- custom logo --- custom title at each message. Thanks in advance.

prasanna - 5/26/2016
Hello, I have gone through this article.It is very nice. I want to introduce a new push notification service called Pushify, which offers you Unlimited Free Browser Push Notifications to Unlimited Subscribers by which you can connect with your customers easily even customer not in your website. Notifications will deliver to your Customers Mobile and Desktop. We are offering Unlimited REST API calls, Geo-Targeting, Scheduled Notifications, Free Plugins to CMS & e-commerce, RSS 2 Push and many features for free. To know more just visit www.pushify.com

Ryan - 10/5/2016
Since, there are various tech specification changes going on every now and then, it would be wise to stick to your own business and let services like www.pushassist.com handle the push notification on your behalf. You don't only need Chrome, you need it to work on FireFox and Safari too. Try a free account and see it up and running under 2 minutes.

Blia - 10/10/2016
Is there a way to use the received notification body and title instead of hard coding in the notification? I've looked at examples by Google and they are all hard coding their examples. Thanks in advance!

Muneeb Ali - 11/1/2016
Hi,I want to send a form data like title, msg as a notification

rtgrthgrtg - 7/31/2017
rtrthgt thtrhytr trythyrt rtyrt rrtytr eretg etete etetet eteter

11 - 12/25/2017

Add your comment

300 Characters left

Please fill this in to confirm that you are human