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

Service Workers

Service Workers

Push Notifications, Offline Mode, and Background Sync with Service Workers

Arnelle Balane

May 04, 2016
Tweet

More Decks by Arnelle Balane

Other Decks in Programming

Transcript

  1. Service Workers provide the foundation that these features can rely

    on Push Notifications Background Sync Offline Mode
  2. NO

  3. asyncOne(function() { asyncTwo(function() { asyncThree(function() { // callback hell });

    }); }); asyncOne() .then(asyncTwo) .then(asyncThree) .catch(function(error) { // handle error }); traditional callbacks using promises Service Workers make extensive use of promises
  4. Web APIs that are asynchronous (such as asynchronous XHR and

    localStorage) are not accessible inside service workers. Designed to be fully asynchronous
  5. Installing a ServiceWorker service-worker.js self.addEventListener('activate', function(event) { // This service

    worker is now the active one! // The previous version (if any) has already been removed by the browser. });
  6. Support Detection if ('Notification' in window) { // Yay we

    can show notifications! } Check support for notifications
  7. Support Detection if (Notification.permission !== 'denied') { // Yay the

    user did not block notifications! } Check whether the user blocked notifications
  8. Support Detection if ('PushManager' in window) { // Yay we

    have support for push notifications! } Check support for push notifications
  9. Subscribing to Push Notifications registration.pushManager.subscribe().then(function(subscription) { // Yay we are

    not registered to push notifications! // Now let's get our subscription token! }); Chrome: need to pass { userVisibleOnly: true } to subscribe() call.
  10. Subscription Token subscription parameter is an object with a key

    called endpoint, which might look like this: https://android.googleapis. com/gcm/send/APA91bHPffi8zclbIBDcToXN_LEpT6iA87pgR-J-MuuVVycM0SmptG- rXdCPKTM5pvKiHk2Ts-ukL1KV8exGOnurOAKdbvH9jcvg8h2gSi- zZJyToiiydjAJW6Fa9mE3_7vsNIgzF28KGspVmLUpMgYLBd1rxaVh- L4NDzD7HyTkhFOfwWiyVdKh__rEt15W9n2o6cZ8nxrP
  11. Subscription Token subscription parameter is an object with a key

    called endpoint, which might look like this: https://android.googleapis. com/gcm/send/APA91bHPffi8zclbIBDcToXN_LEpT6iA87pgR-J-MuuVVycM0SmptG- rXdCPKTM5pvKiHk2Ts-ukL1KV8exGOnurOAKdbvH9jcvg8h2gSi- zZJyToiiydjAJW6Fa9mE3_7vsNIgzF28KGspVmLUpMgYLBd1rxaVh- L4NDzD7HyTkhFOfwWiyVdKh__rEt15W9n2o6cZ8nxrP
  12. Unsubscribing from Push Notifications registration.pushManager.getSubscription().then(function(subscription) { if (subscription) { subscription.unsubscribe().then(function()

    { // Unsubscribe successful! }); } else { // We are not yet subscribed for push notifications. } }) Chrome: need to pass { userVisibleOnly: true } to subscribe() method.
  13. Displaying a notification service-worker.js self.addEventListener('push', function(event) { var title =

    'Notification Title'; var body = 'Notification Body'; var icon = '/path/to/icon.png'; event.waitUntil( self.registration.showNotification(title, { body: body, icon: icon }); ); });
  14. A Google Cloud Platform service that enables developers to send

    messages between servers and client applications or vice versa. Handles all aspects of the message transfer, from queueing of the messages up to their delivery to and from the client applications. Google Cloud Messaging
  15. Send a request to GCM with the following information: url:

    https://android.googleapis.com/gcm/send method: POST headers: Authorization: key=GCM_SERVER_KEY Content-Type: application/json Data: <GOOGLE_CLOUD_MESSAGING_OPTIONS> Sending notification from server to GCM
  16. to Specifies the subscription token of the recipient registration_ids Specifies

    a list of subscription tokens for multiple recipients collapse_key Identifies a group of messages that can be collapsed, meaning that only the latest message with this key will be delivered to the client time_to_live Specifies how long (in seconds) the message should be kept in GCM storage while the client is still offline notification Specifies a predefined notifications object Google Cloud Messaging options
  17. - Can’t pass data along with the push notification -

    Can’t get list of visible notifications for programmatic closing - Notifications can only be userVisibleOnly - On mobile, predefined notification data only appears when Chrome is closed - On desktop, when Chrome is closed, push notifications won’t be received Push Notifications - The ಠ╭╮ಠ Parts
  18. Caching Resources service-worker.js var CACHE_NAME = 'sw-cache'; self.addEventListener('install', function(event) {

    event.waitUntil( caches.open(CACHE_NAME).then(function(cache) { // Cache successfully opened! }) ); }); Open a cache
  19. Caching Resources service-worker.js var CACHE_NAME = 'sw-cache'; self.addEventListener('install', function(event) {

    event.waitUntil( caches.open(CACHE_NAME).then(function(cache) { return cache.add('/some/file.png'); }) ); }); Add resource paths to the cache
  20. Caching Resources service-worker.js var CACHE_NAME = 'sw-cache'; self.addEventListener('install', function(event) {

    event.waitUntil( caches.open(CACHE_NAME).then(function(cache) { return cache.addAll([ '/', '/some/file.png' ]); }) ); }); Add resource paths to the cache
  21. service-worker.js var CACHE_NAME = 'sw-cache'; self.addEventListener('activate', function(event) { event.waitUntil( caches.keys().then(function(keys)

    { return Promise.all(keys.map(function(key) { if (key !== CACHE_NAME) return caches.delete(key); })); }); ); }); Deleting old cache versions
  22. '/service-worker.js' ⇒ scope: '/' - Fires 'fetch' events for all

    network requests '/static/service-worker.js' ⇒ scope: '/static' - Fires 'fetch' events only for requests with paths that start with '/static' - Won’t fire 'fetch' event for e.g. '/images/sample.png' ServiceWorker Scope
  23. - Only GET requests can be cached - Can also

    cache resources from other origins - Can also dynamically cache requested resources - Due to the ability to intercept network requests, Service Workers need to be served over HTTPS for security purposes Offline Mode - Other Stuff
  24. Background Sync flowchart some data to be sent to server

    server supports background sync? send data to server the usual way save data to IndexedDB ( ゚ヮ゚) ONLINE!!! NO register to background sync YES
  25. Registering for Background Sync registration.sync.register('send-message').then(function() { // Now registered for

    background sync! // Next, save the message to a persistent storage. }); The 'send-message' string passed to the register() method is a tag, which can be checked in the service worker to determine how it should send the data to the server.
  26. Knowing if we can already sync to server service-worker.js self.addEventListener('sync',

    function(event) { if (event.tag === 'send-message') { // Retrieve from persistent storage those objects that are tagged // as 'send-message'. } }); One 'sync' event for each unique registered tag.