Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Service Workers - Beyond The Cache (NDC Sydney)

Phil Nash
September 19, 2018

Service Workers - Beyond The Cache (NDC Sydney)

Service workers are here to stay, they're live in (almost!) all the major browsers and all your favourite frameworks offer them out of the box for caching your application offline. This is a great start for building modern, resilient, progressive web applications. But only using the service worker's cache is like driving a sports car in 3rd gear at the most.

We'll dive into push notifications, background sync and other experimental service worker features, showing what they can be used for and how to integrate them in your app. Together we'll see how to make your web apps appier and your users happier.

--

Links:

The demo app: https://github.com/philnash/sms-messages-app

Push notification docs: https://developers.google.com/web/fundamentals/codelabs/push-notifications/
Web push libs: https://github.com/web-push-libs
UX of push notification permissions: https://developers.google.com/web/fundamentals/push-notifications/permission-ux
Permissions on the web suck: https://philna.sh/blog/2018/01/08/permissions-on-the-web-suck/

Background sync example: https://www.twilio.com/blog/2017/02/send-messages-when-youre-back-online-with-service-workers-and-background-sync.html

Experimenting with background fetch: https://philna.sh/blog/2017/07/04/experimenting-with-the-background-fetch-api/

Phil Nash

September 19, 2018
Tweet

More Decks by Phil Nash

Other Decks in Programming

Transcript

  1. Timely noti cations "Daisy just sent you a message" "Your

    car is here now" "You can check in now" @philnash
  2. IN TIME AT THE RIGHT TIME OF DAY, IN THE

    RIGHT TIME ZONE, THE RIGHT NUMBER OF NOTIFICATIONS @philnash
  3. Actionable noti cations "Daisy sent you a message" "Your car

    is here now" "You can check in now" @philnash
  4. Personal noti cations "Daisy sent you a message" "Your car

    is here" "You can check in now" @philnash
  5. VAPID Subscribe to push noti cations with public key Sign

    a JWT with private key when sending a push This identi es your application @philnash
  6. Subscribe to noti cations navigator.serviceWorker.ready.then(registration => { registration.pushManager .subscribe({ userVisibleOnly:

    true, applicationServerKey: convertedVapidKey }) }); 01. 02. 03. 04. 05. 06. 07. @philnash
  7. Subscribe to noti cations registration.pushManager.subscribe({ ... }).then(subscription => { fetch('/push/subscription',

    { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(subscription.toJSON()) }); }); 01. 02. 03. 04. 05. 06. 07. @philnash
  8. Send Noti cation (Node.js) const webPush = require('web-push'); webPush.setVapidDetails( 'mailto:[email protected]',

    config.vapidPublicKey, config.vapidPrivateKey ); 01. 02. 03. 04. 05. 06. @philnash
  9. Send Noti cation (C#) using WebPush; var subscription = new

    PushSubscription(pushEndpoint, p256dh, auth); var vapidDetails = new VapidDetails(subject, publicKey, privateKey); var webPushClient = new WebPushClient(); webPushClient.SendNotification(subscription, "payload", vapidDetails); 01. 02. 03. 04. 05. 06. @philnash
  10. Receive noti cation (service worker) self.addEventListener('push', event => { const

    data = event.data.json(); event.waitUntil( self.registration.showNotification(data.title, { body: data.body, }) ); }); 01. 02. 03. 04. 05. 06. 07. 08. @philnash
  11. Ketan Joshi @KetanJ0 Dear website, - I don't want you

    to post notifications to my desktop - I don't want to subscribe to your thing via a popup - I don't want you to know my location - Please stop autoplaying that video - I am angry and sad now 7:17 PM - May 13, 2018 31K 8,535 people are talking about this @philnash
  12. Background sync • Sending messages • Posting comments • Adding

    to a shopping cart • Liking or favouriting @philnash
  13. The plan 1. Request fails due to network 2. Save

    request data in IndexedDB 3. User comes back online 4. Sync event res, replay request @philnash
  14. Register for Sync event fetch(url, { ... }).catch(err => {

    navigator.serviceWorker.ready.then(reg => { saveDataToIndexedDB(); reg.sync.register('fail'); }); }); 01. 02. 03. 04. 05. 06. @philnash
  15. Workbox const bgSyncPlugin = new workbox.backgroundSync.Plugin('myQueueName', { maxRetentionTime: 24 *

    60 // Retry for max of 24 Hours }); workbox.routing.registerRoute( /\/api\/.*\/*.json/, workbox.strategies.networkOnly({ plugins: [bgSyncPlugin] }), 'POST' ); 01. 02. 03. 04. 05. 06. 07. 08. 09. 10. @philnash
  16. On the page navigator.serviceWorker.ready.then(function(reg) { const url = "https://example.com/largeFile.mp3"; reg.backgroundFetch.fetch('downloads',

    [url], { icons: [], title: 'Downloading largeFile.mp3', totalDownloadSize: 1048576 }); }); 01. 02. 03. 04. 05. 06. 07. 08. @philnash
  17. In the service worker self.addEventListener('backgroundfetched', function(event) { if (event.tag ===

    'downloads') { event.updateUI('largeFile.mp3 downloaded.'); // add the file to the cache } }); 01. 02. 03. 04. 05. 06. @philnash
  18. Icon Credits • Browser by Kimmi Studio from the Noun

    Project • Cloud by Kimmi Studio from the Noun Project • Gears by TS Graphics from the Noun Project • wi by i cons from the Noun Project @philnash