Web Push API
Browsers that support web push api to manage user subscriptions and to send notifications to the subscribers. Chrome, Firefox browsers have adapted to service workers to help run services in the background, web push notifications being one of those services. All the leading browsers – Chrome, Firefox, Safari now support web push notifications. While the world is still getting adapted to this powerful communication channel, other browsers are joining the bandwagon, Edge and Opera browsers being the latest additions to this list. And at the same time, we see that the existing browsers – Chrome, Firefox are improving upon their web push methodologies by releasing updates in the latest versions. Browser updates can be overwhelming and website owners often find it difficult to follow the different implementation methodologies set by browsers and keep up with the updates. And hence the website owner would typically turn to third-party service providers such as iZooto to implement web push. It’s an advisable approach, considering the efforts involved in setting this scratch up, however, as a website developer, you should be aware of what goes in the background.
There are two ways through which browsers have exposed web push functionality – - Using service workers, followed by Chrome, Firefox. - The Safari way using push packages.
Getting started with iZooto takes less than 5 minutes
The Service-Worker Approach
Service worker is an event driven worker registered in the browser, it’s a JavaScript file that can control the webpage it is associated with by intercepting and modifying navigation and resource requests, caching resources to control offline behavior. Using service workers one can hijack and control connections, fabricate responses. Powerful stuff. Hence service workers are allowed to run only on HTTPS domains. Service workers run asynchronously with the web pages and handle web push events for users. .
Before we dive deep into the details of web push API, let’s see how the web push operates. It constitutes three important workflows as mentioned below
1. Subscribing to notifications : Whenever a website visitor allows for notifications, the registered service worker creates a unique subscription ID, it’s typically saved by an application server. This subscription ID is used to uniquely identify the user and to send a notification.
2. Sending notification : During this step, the application server connects with and requests push service to deliver notifications to the subscribers. Once this request reaches user’s end-point, service worker takes care of showing a notification to the subscriber.
3. Unsubscribing from notifications : Whenever a subscriber resets the notification permission for a website, the subscription ID is removed from the push server. The application server can also mark the subscription ID for deletion accordingly.
Here is a diagram depicting these workflows
Browsers provide standard web push API calls to support the user flows mentioned above. Let's review these web push APIs briefly.
A. Service Worker APIs
Service worker goes through the following lifecycle :
1. Download : Service worker is downloaded whenever a user accesses the web page controlled by service worker. Even after a service worker is registered, it's downloaded periodically for consistency and updates.
2. Install : As soon as the service worker is downloaded, browser tries to install and activate it. InstallEvent.InstallEvent() creates a new installation object, InstallEvent.activeWorker returns the service worker currently active on the webpage. You can keep listening to service worker install event and prepare supporting stuff such as building cache, defining service worker operations.
You can add listeners for event object to see the installation status and initialize your system accordingly.
self.addEventListener('activate', function(event) { //Your code here});
3. Activate : Whenever a service worker is installed, the browser tries to activate it provided that there is no service worker currently active. If another instance of service worker is already running, the new service worker goes in 'Worker in Waiting' stage. It is activated when the web pages no longer refer to the older service worker.
You can add listeners to check activation status for service worker and proceed further.
self.addEventListener('activate', function(event) { //Your code here});
Service worker also support functional events - fetch, sync, push, which are invoked during the notification delivery. You can go through the detailed documentation here.
B. Subscription prompt APIs
Subscription prompt APIs provide information about users current subscription status and may request the browser to prompt the user for subscription. ,
Notification.permission():s It indicates the current permission given by the user for notifications. Response 'granted' tells that the user has already allowed for notifications, 'denied' indicates that the user chose to block notifications from the site and website can't ask for the notification permission again, 'default' indicates that the user has not responded to the subscription prompt yet and browser may choose to prompt the user for subscription again.
Notification.requestPermission(): With this method, the browser would display subscription prompt to the user asking him to subscribe for notifications.
C. Push APIs
Web apps can request browser push servers to deliver notifications to the subscribed users with push APIs. Push APIs are responsible for delivering notification request at users end, capturing user response against pushed notification. These are browser specific APIs, mentioned below are two sample curl commands supported by Chrome and Firefox browsers respectively.
1. Chrome :
curl --header "Authorization: key=XXXXXXXXXXXX" --header "Content-Type: application/json" https://android.googleapis.com/gcm/send -d "{\"registration_ids\":[\"fs...Tw:APA...SzXha\"]}"
2. FireFox :
curl -I -X POST --header "ttl: 60" "https://updates.push.services.mozilla.com/push/gAAAAABW4ccaidtFYOP2m56-XiY_NSKDXV1QiJ-4cpZG5BF-W7FjWE17SDt-h-b4b4VJamuvL30OcI9msyM1bupE9YHrwQZH4D7Uh2YS8cE_Tpvnvm3CgpBjblH58sE78HQjjbahB5NG4CkkKLj13gz0eB9mOAVGfcM3qo4Z61M5fn_6HZqLvCg="
D. Notification API's :
Notification APIs are used to display an actual notification to the user and to capture their responses. Service worker keeps listening to the push requests in the background. As soon as it receives a request to display notification, it fetches required notification data from the application server and displays a notification to the user.

self.addEventListener('push', function(event) { console.log('Received a push message', event);
var title = 'Yay a message.';
var body = 'We have received a push message.';
var icon = '/images/icon-192x192.png';
var tag = 'simple-push-demo-notification-tag';
self.registration.showNotification(title,{body: body,icon: icon,tag: tag})
Additionally, user responses to the notifications can be tracked using Notification.Event. NotificationEvent.NotificationEvent() creates a new notification object which can be accessed to capture user response to notification. It inherits its properties from parent object - Event, hence all the functions defined for Event object can be accessed by NotificationEvent object. Notification Event object has following properties that store information about the notification which was clicked.
NotificationEvent.notification: Returns the notification object giving information about notification that was clicked.
NotificationEvent.action: Returns the information about a notification button that was clicked.
E. Web App Manifest Configuration
For web push notifications, website domains can define the scope of the implementation. Chrome asks website owners to perform the web app manifest configuration for authentication and security, it also lets you control how the web app would appear to the user. Chrome requires GCM details to be configured in web app manifest to identify the sender uniquely.
It’s a json file. It’s content can co-exist with any other configuration supported by manifest. Contents of a sample configuration file are mentioned below.
{"name": "Myonlineshop", "short_name": "Myonlineshop", "icons": [{ "src": "/logo_192_by_192.png", "sizes": "192x192", "type": "image/png" }], "start_url": "/", "display": "standalone", "gcm_sender_id": "1075877101267", "gcm_user_visible_only": true }
Push notifications seamlessly with iZooto on Chrome, Firefox and Safari
The Safari Way
A. Get website push certificate
Every website is required to create a push certificate through the apple developer account, the developer account provides a simple user interface to create a push certificate for the website.
B. Add notification support to the server
This step deals with taking subscriptions from users and delivering notifications to the subscribers.
1. Take subscription : Every subscription generates a unique ID which can be used as the end-point to deliver notifications. The first step is verifying the user’s current permission for notifications and prompt the user for subscription accordingly as the next step.
a. Query Permission: This API returns the current status of subscription.
var result = window.safari.pushNotification.permission( websitePushID);
result.permission = "default"/"denied"/"granted"
b. Request Permission : This API function asks the browser to prompt the user for subscription. As soon as the user subscribes, a unique ID is created and shared in the callback.
window.safari.pushNotification.requestPermission(webServiceURL,websitePushID, userInfo, callback);
2. Configure web service backend : Once the subscription is completed, following functions can be called to manage device tokens.
/* It's invoked in order to store registrations against the websitePushID in your system. */
POST /v1/devices//registrations/
/* It can be called to log messages in the system. */
POST /v1/log
/* Whenever a user unsubscribes, the device token can be deleted from the system. */
DELETE /v1/devices//registrations/
3. Send push notifications : In the last step, APNS push API is called to deliver notification to the subscriber. Safari notifications operate on payload and hence the notification data is sent along with the push request itself. Following is a snippet of the sample notification request made.
{"aps": {"alert": { "title": "You've", "body": "Your gate has changed to A4.", "action": "View"},"url-args": ["notification-message", "testing a notification"]}}
#Safari is yet to adopt service worker methodology to push notifications