Chrome Push Notifications Example Of Implementation

Chrome push notifications are one of the newer features added into Chrome browser. They are used to show notifications outside the web page context even if the user is not browsing the page he subscribed to.

Before we continue, make sure that you use  https or implement the code on localhost because service workers require secure origins to ensure that the service worker script is from the intended origin and hasn’t come about from a man-in-the-middle attack.

Example of implementation for Chrome push notifications:

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. To get a better understanding of some of the other features of manifests and the offline capabilities of service workers, please check out the links above.

A simple code example can be found on the GoogleChrome Samples Repo.

In our example, notifications work as follows:

User enters the site and browses a category. In javascript we check to see if there is a cookie set with the name “category_notifications_ID” where “ID” is the id of our category in wordpress.

If there is no cookie set with name “category_notifications_ID” we open a modal window where we ask the user if he wants to receive notifications when a new post is added in that specific category.

notification_request_popup

Here we have two choices, No thanks and Accept. Let’s talk about what happens in both cases depending of what the user chooses:

No thanks
In this case we just set a cookie with name “category_notifications_ID” and expire date set to 7 days.

 

Accept
In this case user will be asked by chrome browser to allow or block notifications from this website.

 

Chrome notification request:

 

Allow

If user accepts notifications, we then call the function Chrome Push Manager to register service worker with name service-worker_ID.js, obtain device id and register it.In this case, we use an ajax function to run some php code to store into database register id, category id, and the date of the registration id. This notification popup from chrome appears only one time. If everything works well, we then show to user a success notification and set a cookie with the name “category_notifications_ID” and expire date set to 1 year so that the next time when the user gets to this category  we will not show the popup to allow notifications.

success_popup

Sample code:

Chrome Push Manager sample code:

 

Block

In this case we just set a cookie with name “category_notifications_ID” and expire date set to 1 year as well and dismiss the popup.

notification_cookie

 

 

Send notifications to users when we post a new article

First we  add an action on publish_post in functions.php, so everytime we hit the “Publish” button, it will run our code too as following:

  • check if the modified date is equal to post date. This means that the post is a new entry, not an updated one.
  • get all categories that this post is part of
  • make a foreach through all categories and get registration ids into an array based on category
  • run function “send_gcm_notify()” for each category and send notifications to registered users ids. This function will send a notification to Google Cloud Messaging which will trigger our notification via the service worker registered on your browser.

Sample of send_gcm_notify() function:

Service Worker Push Event Listener

When a push message is received, a push event will be dispatched in your service worker we registered earlier for a specific category.

Sample of service-worker.js:

 

This is it…enjoy engaging with your users! If you have any questions or suggestions, do not hesitate to write a comment below.

Update (Send Chrome Push Notifications with custom text and image)

In this update we will show you how to implement the notifications to send custom text to your subscribers.
In our case we are sending the title of the newely published article as notification title, body as notification description, the featured image of the article as an icon of our notification and the permalink of our article so when user clicks the notification, it will open up a page with the new article.

We are doing this in 2 steps, so let’s start.

1. Add a file named json-data.php to the root, next to wp-config.php file

Sample code of json-data.php

Let’s talk about the content of this file and why we are using it.

  • Require wp-load.php so you can have access to all wordpress classes and functions.
  • Set json headers
  • Get the latest post id
  • Get the content of the last post (Title, body, featured image, permalink) and put all data intto an array
  • Use json_encode() function to encode your array in JSON and then print it

So basically in this file we have all the data we need for our notification in json format.

2. Edit your service-worker.js file so it will take all the data from the json file we previously created in step 1

Sample code of service-worker.js

Don’t forget to change the path to your .json file.  In this case we added the “?param=”+Math.random()” parameter to our url just to be shure that it will always get the new json and it will not cache it.

The new service worker file works like this:

  • When a notification is received, it will try to fetch the json data from the file we previously talked about
  • If all is ok it will grab the json data in a “data” variable and there you can access your data from the json file.

Note:
Until a subscriber to your notifications returns to your website, the service-worker.js file registered on his browser it will be the one registered at the begining. When visiting your website again, service worker will update itself to the newer version.

 

 

Bogdan Rusu

Working in development for more then 10 years, Bogdan Rusu is the CTO of Design19 web agency. Highly skilled in PHP development and usage of CMS like Wordpress, Magento, Zend framework, but also custom built platforms based on PHP, Bogdan has driven the team to a higher level of proficiency in development.