1 of 36

Intro to Web Push and Notifications

Engagement & re-engagement �for the Web

Progressive Web Apps

Progressive Web Apps

2 of 36

Push notification demos

Progressive Web Apps

3 of 36

What are Push Notifications?

  • Notification API
  • Push API

Progressive Web Apps

4 of 36

Push Notification overview

Client

Web Page

Service worker

User Agent

Push Service

App Server

Progressive Web Apps

5 of 36

The Notification API

Progressive Web Apps

6 of 36

Request permission

Notification.requestPermission(function(status) {

console.log('Notification permission status:', status);

});

Progressive Web Apps

7 of 36

TODO

Screencast of notification permission being requested.

Progressive Web Apps

8 of 36

Invocation

Client

Web Page

Service worker

User Agent

Push Service

App Server

Progressive Web Apps

9 of 36

Display a notification

function displayNotification() {

if (Notification.permission === 'granted') {

navigator.serviceWorker.getRegistration()

.then(function(reg){

reg.showNotification('Hello world!');

});

}

}

Progressive Web Apps

10 of 36

Add notification options

var options = {

body: 'Here is a notification body!',

icon: 'images/example.png',

vibrate: [100, 50, 100],

data: { primaryKey: 1 } // allows us to identify notification

};

reg.showNotification('Hello world!', options);

Progressive Web Apps

11 of 36

TODO

Screencast of notification display

from example on previous page.

Progressive Web Apps

12 of 36

Add notification actions

var options = {

body: 'First notification!',

actions: [

{action: 'explore', title: 'Go to the site', icon: 'img/check.png'},

{action: 'close', title: 'No thank you', icon: 'img/x.png'},

]

};

reg.showNotification('Hello world!', options);

Progressive Web Apps

13 of 36

Progressive Web Apps

14 of 36

Interaction

Client

Web Page

Service worker

User Agent

Push Service

App Server

Progressive Web Apps

15 of 36

Notification interactions

Two notification events you can listen for in a service worker:

  • notificationclose
  • notificationclick

Progressive Web Apps

16 of 36

notificationclose

self.addEventListener('notificationclose', function(event) {

var notification = event.notification;

var primaryKey = notification.data.primaryKey;

console.log('Closed notification: ' + primaryKey);

});

Progressive Web Apps

17 of 36

notificationclick

self.addEventListener('notificationclick', function(event) {

var notification = event.notification;

var action = event.action;

if (action === 'close') {

notification.close();

} else {

clients.openWindow('http://www.example.com');

}

});

Progressive Web Apps

18 of 36

Sending and Receiving Push Notifications

Progressive Web Apps

19 of 36

How it works

  1. The user subscribe to push messaging: the push service used by the browser returns data to enable you to send messages to the user.
  2. Your app saves user data to your server.
  3. Send a push message from your server to the user via the push service.
  4. The user's app handles the push message in a service worker.

Progressive Web Apps

20 of 36

Push API

Client

Web Page

Service worker

User Agent

Push Service

App Server

Progressive Web Apps

21 of 36

Subscribe to the Push service

Client

Web Page

Service worker

User Agent

Push Service

App Server

Progressive Web Apps

22 of 36

Subscribing users

Browser

Server

Check if User is Subscribed

Ask User�To Subscribe

User�Subscribes

Send Subscription

Save Subscription

Progressive Web Apps

23 of 36

Check if user is subscribed

navigator.serviceWorker.ready.then(function(reg) {� reg.pushManager.getSubscription().then(function(sub) {� if (sub == undefined) {� // ask user to register for Push� } else {� // You have subscription, update the database on your server� }� });�});

Progressive Web Apps

24 of 36

Subscribe to the push service

navigator.serviceWorker.getRegistration()

.then(function(reg) {

reg.pushManager.subscribe({

userVisibleOnly: true

}).then(function(sub) {

// send sub.toJSON() to server

});

});

Progressive Web Apps

25 of 36

The subscription object

{

"endpoint": "https://fcm.googleapis.com/fcm/send/f1LsxkKp...",

"keys": {

"p256dh": "BLc4xRzKlKORKWlbdgFaB1oEKgPpWC5cW8OCzVrOQRv-1n ...",

"auth": "5I2Bu2oKdyy9CwL8QVF0NQ=="

}

}

Progressive Web Apps

26 of 36

Send a push message from the server

Progressive Web Apps

27 of 36

Sending messages

End Point

Browser

Generate Message

Sent to�End Point

Sent to Browser

Server

Received�by Browser

Progressive Web Apps

28 of 36

Send a message from the server

var webPush = require('web-push');

var payload = 'Here is a payload!';

var options = {

TTL: 60 // max time in seconds for push service to retry delivery

};

webPush.sendNotification(pushSubscription, payload, options);

Progressive Web Apps

29 of 36

What is VAPID?

  • Voluntary Application Server Identification for Web Push (VAPID) protocol is an optional method to identify your service
  • VAPID uses JSON Web Tokens (JWT) to carry identifying information
  • A JWT contains a three properties called a Claim. The claim has:
    • Audience attribute
    • Subscriber property
    • Expiration time value

Progressive Web Apps

30 of 36

Subscribe with the VAPID public key

var applicationServerPublicKey = 'BLiZBfZJTwbWe_TzKaKuiT8GHqmcFU';

var applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);

swRegistration.pushManager.subscribe({

userVisibleOnly: true,

applicationServerKey: applicationServerKey

});

Progressive Web Apps

31 of 36

Send a message with VAPID

var webPush = require('web-push');

var payload = 'Here is a payload!';

var options = {

vapidDetails: {

subject: 'mailto: example-email@example.com',

publicKey: vapidPublicKey,

privateKey: vapidPrivateKey

}

};

webPush.sendNotification(pushSubscription, payload, options);

Progressive Web Apps

32 of 36

Receiving messages

Client

Web Page

Service worker

User Agent

Push Service

App Server

Progressive Web Apps

33 of 36

Receiving messages

Browser

SW Starts

Handle�Message

Show Notification

Push Arrives

Progressive Web Apps

34 of 36

The push event

self.addEventListener('push', function(e) {

var title = e.data.text();

e.waitUntil(

self.registration.showNotification(title)

);

});

Progressive Web Apps

35 of 36

Lab Overview

  • Notification API
    • Create and configure notifications
    • Handle notification actions
  • Push API
    • Handle the push event
    • Subscribe to the push service
    • Send a push message from a Node.js server
  • Best practices (optional)

Progressive Web Apps

36 of 36

Be aware

WARNING: Do not use private/incognito mode for this lab.

Push notifications are not supported in private/incognito mode for security reasons.

Progressive Web Apps