Sending Push Notifications : Progressive Web Apps
We need permissions to send push notifications.
Key Points :
- Notifications must be timely.
- Should be precise (contains all the information a user needs).
- Should be relevant to the user.
Basic Example : An airline app must send push notifications such as “Your flight will be boarding from…”
Browser that supports push notifications are :
- Chrome 44
- Firefox 44
- Opera 42
Types of Notifications :
- Persistent Notifications: It is associated with the Service Worker.
self.registration.showNotification(
'Title'
, {
actions : [ {
action :
'View'
,
title :
'Action title'
,
icon :
'Path'
}],
// other options});
To Interact with them, there is different API :
self.addEventListener(
'notificationclick'
, evt=>{
if
(!evt.action)
{
Console.log(
'Notification Clicked'
);
return
;
}
// Handles action clicks
});
View :
self.addEventListener(
'notificationclick'
, evt=>{
switch
(evt.action) {
case
'view'
: Console.log(
'View action clicked'
);
break
;
default
: Console.warn(
'${evt.action}action clicked'
);
break
;
}});
- Non-Persistent Notifications: It is not associated with the Service Worker. As a developer, we interact with this through the notification API.
Notification Static Member :
if
(Notification.permission ===
'granted'
)
{
showNotification();
return
;
}
if
(Notification.permission !==
'denied'
)
{
Notification.request Permission().then (p=> {
if
(p ===
'granted'
)
showNotification();
});
}
How to show Notification :
var
n =
new
Notification(
'Title'
,
// object
{
body :
'body text'
,
// Little tiny badge at top left
// corner of screen
badge :
'path'
,
// Setting picture related to the
// notification, For Ex: Soda image
// in case of Sodapopped website
icon :
'path'
,
// Combining different Notifications
// by providing them with the same
// tag name
tag :
'tag name'
,
// To notify buzz, set it true
renotify :
false
,
data : {
//object}
);
Different other Properties can also be written in the following format :
var n = new Notification( 'Title' , // body, images, tag, etc. { // True, when notifications remain open until // the user explicitly clicks on it to requiredInteraction : false , close actions : [ { // Takes objects which has three properties action : 'Id' , title : 'Action title' , icon : 'Path' }], }); |
// body, images, tag, data, action // True, vibrate or make sound silent : false , // path to sound (Till date no browser // supports this) sound : 'path' , // This indicates to vibrate for 200ms // then 100ms then 200ms, so on vibrate : [200 100 200], |
// Direction (left to right or right to left(rtl)) dir : 'ltr' , // Language lang : 'en-US' , timestamp : Date.now() // Time |
Notification Instance Member :
var n = new Notification(‘Title’, {//options });
- n.addEventListener(‘error’, evt=>{ Console.error(‘There was a problem’, evt);});
- n.addEventListener(‘click’, evt=>{ Console.log(‘Notification clicked’);});
n.close();
Please Login to comment...