SlideShare une entreprise Scribd logo
1  sur  25
WEB PUSH NOTIFICATIONS
UGUR EKER - BBS #213
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
SERVICE
WORKERS
WEB PUSH NOTIFICATIONS
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
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.
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.
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.
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”.
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.
PUSH API
WEB PUSH NOTIFICATIONS
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.
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.
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;

});
NOTIFICATIONS
API
WEB PUSH NOTIFICATIONS
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.
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.
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.
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);

}

});

}

});
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);

}

})

);

});
FIREBASE CLOUD
MESSAGING
WEB PUSH NOTIFICATIONS
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.
FIREBASE CLOUD MESSAGING
HOW DOES IT WORK?
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
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.
QUESTIONS?

Contenu connexe

En vedette

iOS 10 Rich Push Notifications
iOS 10 Rich Push NotificationsiOS 10 Rich Push Notifications
iOS 10 Rich Push NotificationsinFullMobile
 
Brug - Web push notification
Brug  - Web push notificationBrug  - Web push notification
Brug - Web push notificationOlga Lavrentieva
 
Push Notifications
Push NotificationsPush Notifications
Push NotificationsCocoaHeads
 
Matinale Mobile : "L’impact grandissant du mobile sur le retail"
Matinale Mobile : "L’impact grandissant du mobile sur le retail"Matinale Mobile : "L’impact grandissant du mobile sur le retail"
Matinale Mobile : "L’impact grandissant du mobile sur le retail"Mobile Marketing Association France
 
Jump into cross platform development with firebase
Jump into cross platform development with firebaseJump into cross platform development with firebase
Jump into cross platform development with firebaseConstantine Mars
 
Algoritma perulangan
Algoritma perulanganAlgoritma perulangan
Algoritma perulanganazkiyaku
 
Юрий Василевский — Сервис пуш-сообщений Яндекса
Юрий Василевский — Сервис пуш-сообщений ЯндексаЮрий Василевский — Сервис пуш-сообщений Яндекса
Юрий Василевский — Сервис пуш-сообщений ЯндексаYandex
 
Firebase - A real-time server
Firebase - A real-time serverFirebase - A real-time server
Firebase - A real-time serverAneeq Anwar
 
Notifications Push : chiffres clés, enjeux, nouveautés...
Notifications Push : chiffres clés, enjeux, nouveautés...Notifications Push : chiffres clés, enjeux, nouveautés...
Notifications Push : chiffres clés, enjeux, nouveautés...Accengage
 
NodeMCU with Blynk and Firebase
NodeMCU with Blynk and FirebaseNodeMCU with Blynk and Firebase
NodeMCU with Blynk and FirebaseEueung Mulyana
 
Web Push уведомления - успешные кейсы, проблемы и статистика инструмента
Web Push уведомления - успешные кейсы, проблемы и статистика инструментаWeb Push уведомления - успешные кейсы, проблемы и статистика инструмента
Web Push уведомления - успешные кейсы, проблемы и статистика инструментаUAMASTER Digital Agency
 
Introduction to Firebase [Google I/O Extended Bangkok 2016]
Introduction to Firebase [Google I/O Extended Bangkok 2016]Introduction to Firebase [Google I/O Extended Bangkok 2016]
Introduction to Firebase [Google I/O Extended Bangkok 2016]Sittiphol Phanvilai
 
Adapt or Die: Serverless Microservices
Adapt or Die: Serverless MicroservicesAdapt or Die: Serverless Microservices
Adapt or Die: Serverless MicroservicesApigee | Google Cloud
 
Petit-Déjeuner du Marketing Mobile : « Comment les marques doivent s’engager ...
Petit-Déjeuner du Marketing Mobile : « Comment les marques doivent s’engager ...Petit-Déjeuner du Marketing Mobile : « Comment les marques doivent s’engager ...
Petit-Déjeuner du Marketing Mobile : « Comment les marques doivent s’engager ...Mobile Marketing Association France
 

En vedette (15)

iOS 10 Rich Push Notifications
iOS 10 Rich Push NotificationsiOS 10 Rich Push Notifications
iOS 10 Rich Push Notifications
 
Brug - Web push notification
Brug  - Web push notificationBrug  - Web push notification
Brug - Web push notification
 
Push Notifications
Push NotificationsPush Notifications
Push Notifications
 
Matinale Mobile : "L’impact grandissant du mobile sur le retail"
Matinale Mobile : "L’impact grandissant du mobile sur le retail"Matinale Mobile : "L’impact grandissant du mobile sur le retail"
Matinale Mobile : "L’impact grandissant du mobile sur le retail"
 
Jump into cross platform development with firebase
Jump into cross platform development with firebaseJump into cross platform development with firebase
Jump into cross platform development with firebase
 
Algoritma perulangan
Algoritma perulanganAlgoritma perulangan
Algoritma perulangan
 
Юрий Василевский — Сервис пуш-сообщений Яндекса
Юрий Василевский — Сервис пуш-сообщений ЯндексаЮрий Василевский — Сервис пуш-сообщений Яндекса
Юрий Василевский — Сервис пуш-сообщений Яндекса
 
Firebase - A real-time server
Firebase - A real-time serverFirebase - A real-time server
Firebase - A real-time server
 
Notifications Push : chiffres clés, enjeux, nouveautés...
Notifications Push : chiffres clés, enjeux, nouveautés...Notifications Push : chiffres clés, enjeux, nouveautés...
Notifications Push : chiffres clés, enjeux, nouveautés...
 
NodeMCU with Blynk and Firebase
NodeMCU with Blynk and FirebaseNodeMCU with Blynk and Firebase
NodeMCU with Blynk and Firebase
 
Web Push уведомления - успешные кейсы, проблемы и статистика инструмента
Web Push уведомления - успешные кейсы, проблемы и статистика инструментаWeb Push уведомления - успешные кейсы, проблемы и статистика инструмента
Web Push уведомления - успешные кейсы, проблемы и статистика инструмента
 
Introduction to Firebase [Google I/O Extended Bangkok 2016]
Introduction to Firebase [Google I/O Extended Bangkok 2016]Introduction to Firebase [Google I/O Extended Bangkok 2016]
Introduction to Firebase [Google I/O Extended Bangkok 2016]
 
Adapt or Die: Serverless Microservices
Adapt or Die: Serverless MicroservicesAdapt or Die: Serverless Microservices
Adapt or Die: Serverless Microservices
 
3wks Google Cloud Next17 Top Ten
3wks Google Cloud Next17 Top Ten3wks Google Cloud Next17 Top Ten
3wks Google Cloud Next17 Top Ten
 
Petit-Déjeuner du Marketing Mobile : « Comment les marques doivent s’engager ...
Petit-Déjeuner du Marketing Mobile : « Comment les marques doivent s’engager ...Petit-Déjeuner du Marketing Mobile : « Comment les marques doivent s’engager ...
Petit-Déjeuner du Marketing Mobile : « Comment les marques doivent s’engager ...
 

Similaire à Web Push Notifications

Offline progressive web apps with NodeJS and React
Offline progressive web apps with NodeJS and ReactOffline progressive web apps with NodeJS and React
Offline progressive web apps with NodeJS and ReactIlia Idakiev
 
Angular Offline Progressive Web Apps With NodeJS
Angular Offline Progressive Web Apps With NodeJSAngular Offline Progressive Web Apps With NodeJS
Angular Offline Progressive Web Apps With NodeJSIlia Idakiev
 
Introduction to Offline Progressive Web Applications
Introduction to Offline Progressive Web ApplicationsIntroduction to Offline Progressive Web Applications
Introduction to Offline Progressive Web ApplicationsIlia Idakiev
 
The web - What it has, what it lacks and where it must go - Istanbul
The web - What it has, what it lacks and where it must go - IstanbulThe web - What it has, what it lacks and where it must go - Istanbul
The web - What it has, what it lacks and where it must go - IstanbulRobert Nyman
 
Push Notification in IBM MobileFirst Xamarin SDK
Push Notification in IBM MobileFirst Xamarin SDKPush Notification in IBM MobileFirst Xamarin SDK
Push Notification in IBM MobileFirst Xamarin SDKAjay Chebbi
 
Push notification to the open web
Push notification to the open webPush notification to the open web
Push notification to the open webAhmed Gamal
 
The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...
The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...
The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...Robert Nyman
 
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd Sencha
 
The web - What it has, what it lacks and where it must go - keynote at Riga D...
The web - What it has, what it lacks and where it must go - keynote at Riga D...The web - What it has, what it lacks and where it must go - keynote at Riga D...
The web - What it has, what it lacks and where it must go - keynote at Riga D...Robert Nyman
 
Unicenter Autosys Job Management
Unicenter Autosys Job ManagementUnicenter Autosys Job Management
Unicenter Autosys Job ManagementVenkata Duvvuri
 
The web - What it has, what it lacks and where it must go
The web - What it has, what it lacks and where it must goThe web - What it has, what it lacks and where it must go
The web - What it has, what it lacks and where it must goRobert Nyman
 
Loadrunner interview questions and answers
Loadrunner interview questions and answersLoadrunner interview questions and answers
Loadrunner interview questions and answersGaruda Trainings
 
Windows Phone 7 Unleashed Session 2
Windows Phone 7 Unleashed Session 2Windows Phone 7 Unleashed Session 2
Windows Phone 7 Unleashed Session 2Wes Yanaga
 
Andrii Dembitskyi "Events in our applications Event bus and distributed systems"
Andrii Dembitskyi "Events in our applications Event bus and distributed systems"Andrii Dembitskyi "Events in our applications Event bus and distributed systems"
Andrii Dembitskyi "Events in our applications Event bus and distributed systems"Fwdays
 
AWS April Webinar Series - Easily Build and Scale Mobile Apps with AWS Mobile...
AWS April Webinar Series - Easily Build and Scale Mobile Apps with AWS Mobile...AWS April Webinar Series - Easily Build and Scale Mobile Apps with AWS Mobile...
AWS April Webinar Series - Easily Build and Scale Mobile Apps with AWS Mobile...Amazon Web Services
 
Service workers and their role in PWAs
Service workers and their role in PWAsService workers and their role in PWAs
Service workers and their role in PWAsIpsha Bhidonia
 
Tips and Tricks for new async web client capabilities on model driven apps
Tips and Tricks for new async web client capabilities on model driven appsTips and Tricks for new async web client capabilities on model driven apps
Tips and Tricks for new async web client capabilities on model driven appsMehdi El Amri
 

Similaire à Web Push Notifications (20)

Offline progressive web apps with NodeJS and React
Offline progressive web apps with NodeJS and ReactOffline progressive web apps with NodeJS and React
Offline progressive web apps with NodeJS and React
 
Angular Offline Progressive Web Apps With NodeJS
Angular Offline Progressive Web Apps With NodeJSAngular Offline Progressive Web Apps With NodeJS
Angular Offline Progressive Web Apps With NodeJS
 
Introduction to Offline Progressive Web Applications
Introduction to Offline Progressive Web ApplicationsIntroduction to Offline Progressive Web Applications
Introduction to Offline Progressive Web Applications
 
Progressive Web Apps
Progressive Web AppsProgressive Web Apps
Progressive Web Apps
 
The web - What it has, what it lacks and where it must go - Istanbul
The web - What it has, what it lacks and where it must go - IstanbulThe web - What it has, what it lacks and where it must go - Istanbul
The web - What it has, what it lacks and where it must go - Istanbul
 
Push Notification in IBM MobileFirst Xamarin SDK
Push Notification in IBM MobileFirst Xamarin SDKPush Notification in IBM MobileFirst Xamarin SDK
Push Notification in IBM MobileFirst Xamarin SDK
 
Push notification to the open web
Push notification to the open webPush notification to the open web
Push notification to the open web
 
The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...
The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...
The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...
 
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
 
GDG Ibadan #pwa
GDG Ibadan #pwaGDG Ibadan #pwa
GDG Ibadan #pwa
 
The web - What it has, what it lacks and where it must go - keynote at Riga D...
The web - What it has, what it lacks and where it must go - keynote at Riga D...The web - What it has, what it lacks and where it must go - keynote at Riga D...
The web - What it has, what it lacks and where it must go - keynote at Riga D...
 
Unicenter Autosys Job Management
Unicenter Autosys Job ManagementUnicenter Autosys Job Management
Unicenter Autosys Job Management
 
The web - What it has, what it lacks and where it must go
The web - What it has, what it lacks and where it must goThe web - What it has, what it lacks and where it must go
The web - What it has, what it lacks and where it must go
 
Loadrunner interview questions and answers
Loadrunner interview questions and answersLoadrunner interview questions and answers
Loadrunner interview questions and answers
 
Windows Phone 7 Unleashed Session 2
Windows Phone 7 Unleashed Session 2Windows Phone 7 Unleashed Session 2
Windows Phone 7 Unleashed Session 2
 
Andrii Dembitskyi "Events in our applications Event bus and distributed systems"
Andrii Dembitskyi "Events in our applications Event bus and distributed systems"Andrii Dembitskyi "Events in our applications Event bus and distributed systems"
Andrii Dembitskyi "Events in our applications Event bus and distributed systems"
 
AWS April Webinar Series - Easily Build and Scale Mobile Apps with AWS Mobile...
AWS April Webinar Series - Easily Build and Scale Mobile Apps with AWS Mobile...AWS April Webinar Series - Easily Build and Scale Mobile Apps with AWS Mobile...
AWS April Webinar Series - Easily Build and Scale Mobile Apps with AWS Mobile...
 
Service workers and their role in PWAs
Service workers and their role in PWAsService workers and their role in PWAs
Service workers and their role in PWAs
 
Tips and Tricks for new async web client capabilities on model driven apps
Tips and Tricks for new async web client capabilities on model driven appsTips and Tricks for new async web client capabilities on model driven apps
Tips and Tricks for new async web client capabilities on model driven apps
 
Bucruiser ppt
Bucruiser pptBucruiser ppt
Bucruiser ppt
 

Dernier

Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Sonam Pathan
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一Fs
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxDyna Gilbert
 
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Lucknow
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)Christopher H Felton
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Sonam Pathan
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Excelmac1
 
Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMartaLoveguard
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一Fs
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa494f574xmv
 
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationLinaWolf1
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhimiss dipika
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Dana Luther
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITMgdsc13
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Paul Calvano
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一z xss
 

Dernier (20)

Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptx
 
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
 
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja VipCall Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
Call Girls Service Adil Nagar 7001305949 Need escorts Service Pooja Vip
 
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...
 
Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptx
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa
 
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 Documentation
 
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhi
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITM
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
 

Web Push Notifications

  • 1. WEB PUSH NOTIFICATIONS UGUR EKER - BBS #213
  • 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.
  • 10. PUSH API WEB PUSH NOTIFICATIONS
  • 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.