Live version of slide deck
https://slides.com/capouch/pwa/live
brianc@palaver.net
danilozeka93@gmail.com
Service worker code to implement proxy cache - ~/public/sw.js:21
self.addEventListener('fetch', function(event) {
console.log('SW Intercepting: ' + event.request.url);
event.respondWith(
caches.match(event.request).then(function(response) {
// Cache hit - return response
//return response || fetch(event.request);
if (response){
console.log("Returning cached value for: " + event.request.url);
return response;
}
// No hit; fetch resource
return fetch(event.request);
})
);
});
~/app/components/views/Subscribe.js:113
// Service routines to handle subscription activities
function subscribeUser() {
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
})
.then(function(subscription) {
console.log('User is subscribed.');
updateSubscriptionOnServer(subscription);
isSubscribed = true;
})
.catch(function(err) {
console.log('Failed to subscribe the user: ', err);
});
}
Routine to send push notification: ~/server/routes.js:25
const pushOptions = {
vapidDetails: {
subject: 'mailto:' + vapidKeys.EMAIL,
publicKey: vapidKeys.PUBLIC_KEY,
privateKey: vapidKeys.PRIVATE_KEY
},
}
webPush.sendNotification(
subscription,
payload,
pushOptions
)
Show the user the notification message - ~/public/sw.js:38
// Copied from https://developers.google.com/web/fundamentals/engage-and-retain/push-notifications/good-notification
self.addEventListener('push', event => {
let thisMessage = event.data.text()
console.log("We got this message: " + thisMessage)
console.log('[Service Worker] Push Received.');
console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);
const title = 'PWA';
const options = {
body: thisMessage,
// We didn't implement these pieces
icon: 'images/icon.png',
badge: 'images/badge.png'
};
event.waitUntil(self.registration.showNotification(title, options));
})