2. WEB PUSH NOTIFICATIONS
AGENDA
‣ Service Workers
‣ Concept
‣ Life Cycle
‣ Basic Architecture
‣ Promises
‣ Events
‣ Push API
‣ Concept & Usage
‣ Events
‣ 3rd Party Services
‣ Notifications API
‣ Concept & Usage
‣ Creating a Notification
‣ Firebase Cloud Messaging
‣ How does it work
‣ Useful Features
‣ Lifetime of a Message
4. SERVICE WORKERS
WHAT IS SERVICE WORKER?
A service worker is an event-driven worker script that your browser
runs in the background.
‣ Associated with web page / site
‣ Runs in separate thread in browser. (Does not interrupt page load)
‣ Can not access DOM directly
‣ Can not use XHR and localStorage
‣ Works over HTTPS
‣ Can run async operations with promises
5. SERVICE WORKERS
Service workers act as proxy servers that stands between
web applications, and the browser and network.
Intercept network requests and takes appropriate action
based on network status and request.
6. SERVICE WORKERS
LIFECYCLE
DOWNLOAD
‣ The service worker is
immediately downloaded
when a user first accesses a
service worker–controlled
site/page.
‣ After that it is downloaded
every 24 hours at most.
‣ Installation is attempted when
the downloaded file is found
to be new — either different to
an existing service worker
(byte-wise compared), or the
first service worker
encountered for this page/
site.
INSTALL
‣ If there is an existing
service worker
available, the new
version is installed in
the background, but
not yet activated — at
this point it is called
the worker in waiting.
‣ It is only activated
when there are no
longer any pages
loaded that are still
using the old service
worker.
ACTIVATE
‣ When the service
worker is installed, it
then receives an
activate event. The
primary use of
onactivate is for
cleanup of resources
used in previous
versions of a Service
worker script.
‣ The Service worker
will now control
pages, but only those
opened after the
register() is
successful.
7. SERVICE WORKERS
BASIC ARCHITECTURE
▸ The service worker URL is fetched and registered via serviceWorkerContainer.register().
▸ If successful, the service worker is executed in a ServiceWorkerGlobalScope. (RO
properties and Global Event Handlers)
▸ The service worker is now ready to process events.
▸ Installation of the worker is attempted when service worker-controlled pages are accessed
subsequently. Runs onInstall events.
▸ When the onInstall handler completes, the service worker is considered installed.
▸ When the service worker is installed, it then receives an activate event. The primary use of
onactivate is for cleanup of resources used in previous versions of a Service worker script.
▸ The Service worker will now control pages, but only those opened after the register() is
successful.
8. SERVICE WORKERS
PROMISES
▸ Promises are a mechanism for running asynchronous
computations, with success dependant on one another.
▸ A Promise object has three states including “pending”,
“fulfilled” and “rejected”.
9. SERVICE WORKERS
EVENTS
▸ statechange: The state attribute of the ServiceWorker
object is changed.
▸ controllerchange: Active service worker changes.
▸ updatefound: The service worker registration's installing
worker changes.
▸ error: On error
▸ push: Push payload received.
11. PUSH API
WHAT IS PUSH API?
The Push API gives web applications the ability to receive
messages pushed to them from a server, whether or not the
web app is in the foreground, or even currently loaded. This
lets developers deliver asynchronous notifications and
updates to users that opt in, resulting in better engagement
with timely new content.
12. PUSH API
CONCEPT & USAGE
For an app to receive push messages, it has to have an active
service worker.
‣ Subscribe: Subscribes a 3rd party push service. And it
returns a promise that resolves PushSubscription object.
‣ PushSubscription: The PushSubscription interface of the
Push API provides a subcription's URL endpoint,
subscription options, subscription ID and allows
unsubscription from a push service.
13. PUSH API
EVENTS
▸ Push: The PushEvent interface of the Push API represents a
push message that has been received. This event is sent to
the global scope of a ServiceWorker. It contains the
information sent from an application server to a
PushSubscription.
self.addEventListener(‘push’, function(event) {
if (!(self.Notification && self.notification.permission === 'granted')) {
return;
}
var data = {};
if (event.data) {
data = event.data.json();
}
var title = data.title || “Notification Title";
var message = data.message || “Notification Content";
var icon = data.payload.icon || “<icon_url.jpg>”;
var custom_data = data.payload.data || false;
});
15. NOTIFICATIONS API
WHAT IS NOTIFICATIONS API?
The Notifications API lets a web page or app send
notifications that are displayed outside the page at the
system level; this lets web apps send information to a user
even if the application is idle or in the background.
16. NOTIFICATIONS API
CONCEPT & USAGE
▸ Before an app can display a notification, the user must grant
the application the right to do so.
▸ Notification.permission property can have three states of user
permission. “default”, “granted” and “denied”.
▸ Notification.requestPermission() method requests permission
to display notifications from the user.
▸ This method accepts a callback function that is called once
the user has responded to the request to display permissions.
17. NOTIFICATIONS API
CREATING A NOTIFICATION
▸ A notification constructor accepts two arguments.
▸ Title string
▸ Options object
▸ Instance properties: actions, badge, body, data, dir, lang, tag, icon,
requreInteraction, silent, timestamp, title, vibrate, renotify, sound, sticky
▸ notificationclick Handler: A handler for the click event. It is triggered each time
the user clicks on the notification.
▸ onerror Handler: A handler for the error event. It is triggered each time the
notification encounters an error.
▸ Notification.close() method: Closes current notification.
18. NOTIFICATIONS API
CREATING A NOTIFICATION
self.addEventListener("push", function(event) {
if (!(self.Notification && self.notification.permission === 'granted')) {
return;
}
var data = {};
if (event.data) {
data = event.data.json();
}
var title = data.title || "Notification Title",
message = data.message || "Notification Content",
icon = data.payload.icon || "<icon_url.jpg>",
custom_data = data.payload.data || false;
var notificationOptions = {
title: title,
body: message,
icon: icon,
url: payload.data.url,
requireInteraction: true
};
if (!("Notification" in window)) {
console.log("This browser does not support desktop notification");
} else if (Notification.permission === "granted") {
return new Notification(title, notificationOptions);
} else if (Notification.permission !== "denied") {
Notification.requestPermission(function (permission) {
if (permission === "granted") {
return new Notification(title, notificationOptions);
}
});
}
});
19. NOTIFICATIONS API
CREATING A NOTIFICATION
self.addEventListener('notificationclick', function(event) {
event.notification.close();
var url = event.notification.url;
event.waitUntil(
clients.matchAll({
type: 'window'
})
.then(function(windowClients) {
for (var i = 0; i < windowClients.length; i++) {
var client = windowClients[i];
if (client.url === url && 'focus' in client) {
return client.focus();
}
}
if (clients.openWindow) {
return clients.openWindow(url);
}
})
);
});
21. FIREBASE CLOUD MESSAGING
FIREBASE CLOUD MESSAGING
▸ Firebase Cloud Messaging (FCM) is a cross-platform messaging
solution that lets you reliably deliver messages at no cost.
▸ FCM is the new version of GCM (Google Cloud Messaging) under the
Firebase brand. It inherits GCM’s core infrastructure, with new SDKs to
make Cloud Messaging development easier.
▸ It provides SDK for iOS, Android, Web, Unity and C++ environments.
▸ Send and receive message from client apps.
▸ Distribute messages to your client app in any of three ways — to single
devices, to groups of devices, or to devices subscribed to topics.
23. FIREBASE CLOUD MESSAGING
USEFUL FEATURES
▸ Works on service worker and in-app
▸ Can give priorities to messages
▸ Messages can be collapsible
▸ Can send custom data
▸ Can set Time To Live
24. FIREBASE CLOUD MESSAGING
LIFETIME OF A MESSAGE
▸ When an app server posts a message to FCM it returns message ID that means message
accepted for delivery.
▸ If device connected but in doze mode, a low priority message is stored by FCM until the
device is out of doze mode. If message is collapsible and a new message with same
collapse key stored, old message is discarded.
▸ If the device is not connected to FCM, the message is stored until a connection is
established (again respecting the collapse key and ttl rules (max 30 days).
▸ If the device has not connected to FCM for more than one month, FCM still accepts the
message but immediately discards it. If the device connects within four weeks of the last
data message you sent to it, your client receives the onDeletedMessages() callback.
▸ Finally, when FCM attempts to deliver a message to the device and the app was
uninstalled, FCM discards that message right away and invalidates the registration token.