Service Worker 201 (en)

61
Service Worker 201 @cwdoh, GDE for Web 1

Transcript of Service Worker 201 (en)

Page 1: Service Worker 201 (en)

Service Worker 201@cwdoh, GDE for Web

1

Page 2: Service Worker 201 (en)

Remind 101Don't you see it? Here it is

2

Page 3: Service Worker 201 (en)

JavaScript codes run on the UI thread

means your code always:

Blocks rendering and all interactions.

Executes scripts when it alives only.

3

Page 4: Service Worker 201 (en)

Web Worker and shared worker are browserfeatures for

Thread‑likely thing for running scripts:

in Background

with message‑passing

 Shared Worker  can be accessed from browsing contexts

4

Page 5: Service Worker 201 (en)

Common rules of Web Worker

Has own global scope

Can't directly manipulate the DOM

Can't use all of properties and method in window scope

5

Page 6: Service Worker 201 (en)

Service WorkerA method that enables applications to take advantage ofpersistent background processing, including hooks to enablebootstrapping of web applications while offline.

6

Page 7: Service Worker 201 (en)

Service Worker is another type of worker:

But, for persistent background processing:

Having an event‑driven model

Managing installation, versions and upgrades

Generic entry point for other specifications

7

Page 8: Service Worker 201 (en)

Comparisons:

Dedicated/Shared Worker and Service Worker

8

Page 9: Service Worker 201 (en)

Dedicated & Shared Worker:

 Runtime ,  Spawning ,  Browsing context 

A thread‑like things can be created at runtime.

You should create Worker and control it at runtime.

Only available when page is loaded and created it.

You should create it at every time when wanna use it again.

9

Page 10: Service Worker 201 (en)

ServiceWorker

 Persistent ,  Installation ,  Browser 

Daemon‑like thing can be install on system aka browser.

Lifecycle is independent from webpage or browser.

Provide version control for update from system

Nicely fits as entry‑points to Remote Notification, BackgroundSync. and so on.

10

Page 11: Service Worker 201 (en)

REMINDER:

Persistent background processing is a goal of service worker,and it decided all of service worker mechanism

11

Page 12: Service Worker 201 (en)

Service Worker ❤ HTTPS

For avoiding  man‐in‐the‐middle‐attack However you can use  127.0.0.1  aka  localhost  without SSLcertificate for testing your module.

12

Page 13: Service Worker 201 (en)

Dive into 201Warm‑up

Working on Offline

Installing shortcut with Web App Manifest

Push Notification

13

Page 14: Service Worker 201 (en)

Warm‑up

14

Page 15: Service Worker 201 (en)

Passing message

a way to interact with Worker :)

.postMessage()

.onmessage

15

Page 16: Service Worker 201 (en)

Message: Client ‑> Worker

index.html

navigator.serviceWorker.controller  .postMessage('hello, worker!');

sw.js

// 페이지로부터 메세지를 포스팅할 때 발생하는 이벤트입니다.self.addEventListener('message', e => {  console.log('Worker got: ' + e.data);});

16

Page 17: Service Worker 201 (en)

Message: Worker ‑> Client

navigator.serviceWorker  .addEventListener('message', e => {  console.log('page got: ' + e.data);});

sw.js

self.addEventListener('message', e => {  // post Message to source client  e.source.postMessage('hello, page!');});

17

Page 19: Service Worker 201 (en)

Simple usage:

navigator.serviceWorker.register('/sw.js') // promise!! .then(function(registration) {     // getting registeration info });

19

Page 20: Service Worker 201 (en)

with option:  scope 

defines the  scope url  that this serviceworker works on.

var options = {  scope: './statics'};

navigator.serviceWorker.register('/sw.js', options) .then(function(registration) {     // getting registeration info });

20

Page 21: Service Worker 201 (en)

importScripts()

Synchronously imports one or more scripts into the worker.

// loading single scriptself.importScripts('perfmatters.js');

// import script for arithmetic operation :)importScripts('add.js', 'minus.js', 'mult.js', 'divide.js');

21

Page 23: Service Worker 201 (en)

Working on Offline

Make your own dinosaurs! :‑p

23

Page 24: Service Worker 201 (en)

To implement offline web app, we'll learn:

1.  Caches  that you have to control

2. How to extend event lifecycle by  .waitUntil() 

3.  fetch  event as network proxy.

24

Page 25: Service Worker 201 (en)

Cache Storage

An interface represents the storage for Cache objects, andreturns  Promise object .

 .match() 

 .has() 

 .open() 

 .delete() 

 .keys() 

25

Page 26: Service Worker 201 (en)

Figure. Named caches in master directories

CacheStorages│├── ServiceWorker_A│   ├── cache.1│   ├── cache.2│   └── cache.3│└── ServiceWorker_B    ├── cache.1    ├── cache.2    └── cache.3

26

Page 27: Service Worker 201 (en)

.waitUntil()

extends current stage

 installing  stage before  install 

 activating  stage before  activate 

27

Page 28: Service Worker 201 (en)

Downloading all resources when first SW is installed.

self.addEventListener('install', function(event) {    predownloadAssets().then(function() {      console.log('finished downloading awesome resoures.');    });});

28

Page 29: Service Worker 201 (en)

ServiceWorker will be activated before download complete.

29

Page 30: Service Worker 201 (en)

Sometimes we need more time to finish current work :)

self.addEventListener('install', function(event) {  // extends current stage, ̀install̀.  event.waitUntil(    predownloadAssets().then(function() {      console.log('finished downloading awesome resoures.');    })  );});

30

Page 31: Service Worker 201 (en)

 .waitUntil()  extends current event stage until given Promiseobject is resolved or failed.

31

Page 32: Service Worker 201 (en)

.onfetch

An event handler fired whenever the browser need to fetch aresource.

32

Page 33: Service Worker 201 (en)

 FetchEvent 

A parameter passed into  .onfetch  handler.

Has information about the request and resulting response

 .respondWith()  to back an custom response to the page

33

Page 34: Service Worker 201 (en)

.respondWith()

Passing response from given  response‐generating‐code parameter to origin.

self.addEventListener('fetch', function(event) {  // custom response with response‐generating‐code  event.respondWith(    // response like typical fetch‐response model    fetch(event.request)      .then(function(res) {        return res;      }).catch(function(error) {        throw error;      })    );});

34

Page 35: Service Worker 201 (en)

Offline sample code

Prefetching resources with  install  event.

Network proxy with  fetch  event.

35

Page 36: Service Worker 201 (en)

Installing shortcut with Web App Manifest

Did you heard  AndroidManifest.xml  of an or  .plist ?

36

Page 37: Service Worker 201 (en)

Web App Manifest defines

a JSON‑based manifest file provides developers with acentralized place to put metadata associated with a webapplication: name, description, author, icon links,orientation and display mode.

37

Page 38: Service Worker 201 (en)

Web App Manifest allows:

Accessing app informations for managing web app

from single JSON file has some metadata

instead of interacting with real page assets.

38

Page 39: Service Worker 201 (en)

How to use it

1. Write your manifest file such as  short_name ,  name ,  icons , ...

{  "short_name": "My superapp",   ...}

2. Link it!

<link rel="manifest" href="YOUR_MANIFEST_URL">

39

Page 40: Service Worker 201 (en)

Add to homescreen

Web app manifests provide the ability to save a site bookmarkto a device's home screen

40

Page 41: Service Worker 201 (en)

Installing shortcut, launching it from homescreen like app.

41

Page 42: Service Worker 201 (en)

Web App Manifest enables to get informations without loading

Displaying app icon and the name on the home screen

Launching what url when user tapped installed icon

42

Page 43: Service Worker 201 (en)

Code

manifest.json

{  "name": "My super powered Web App",  "short_name": "HelloWorld",  "start_url": ".",  "display": "standalone",  "icons": [{    "src": "images/touch/homescreen48.png",    "sizes": "48x48",    "type": "image/png"  },   // ...add your awesome data to define your web app}

43

Page 44: Service Worker 201 (en)

index.html

<head>    ...    <title>My super powered Web App</title>    ...    <link rel="manifest" href="manifest.json">    ...</head>

44

Page 45: Service Worker 201 (en)

Launch styling

Use the  web app manifest  to control the display type and pageorientation, etc. Get more information from here.

{    // Fullscreen mode, set "browser" for showing UI    "display": "standalone",         // Enforcing a specific orientation    "orientation": "landscape",        // set site‐wide theme color on the UI, addressbar    "theme_color": "#2196F3"}

45

Page 46: Service Worker 201 (en)

Web App Install Banner

Automatically ask user  Add to homescreen 

46

Page 47: Service Worker 201 (en)

47

Page 48: Service Worker 201 (en)

Requirements

Page should link  web manifest  with: short_name 

 name 

144x144 png icon (mime type: image/png)

 start_url 

 Service Worker 

 HTTPS 

Be visited at least twicewith at least 5 minutes between visits.

48

Page 49: Service Worker 201 (en)

For test

To ignore visit‑frequency #bypass‐app‐banner‐engagement‐checks 

For desktop #enable‐add‐to‐shelf 

49

Page 50: Service Worker 201 (en)

Sample: manifest.json

{  "name": "My super powered Web App",  "short_name": "HelloWorld",  "start_url": ".",  "display": "standalone",  "icons": [{    "src": "images/touch/homescreen48.png",    "sizes": "48x48",    "type": "image/png"  },   // ...awesome data to define your web app  ],  "related_applications": [{    "platform": "web"  }, {    "platform": "play",    "url": "https://play.goo../details?id=com.android.chrome"  }]}

50

Page 51: Service Worker 201 (en)

Remote Push Notification

A long time ago in a galaxy far, far away...there are spams

51

Page 52: Service Worker 201 (en)

To implement  remote push message , we'll learn:

1.  Push manager  to access push services.

2.  Push subscription  that you have to control

3.  Push event  to handle push event

4.  Push message data  to resolve passing data

52

Page 54: Service Worker 201 (en)

Push manager

The interface defines the operations to access push services.

subscribe(options):

getSubscription():

permissionState(options):

54

Page 55: Service Worker 201 (en)

Push subscription

55

Page 56: Service Worker 201 (en)

Push event

represents a push message that has been received.

sent to the  global scope of a ServiceWorker  aka  onpush 

 .data contains all the information.

56

Page 57: Service Worker 201 (en)

.onpush

An event when fired browser catch a push message.

57

Page 58: Service Worker 201 (en)

Code

event handlers

// ̀push̀ event handler self.addEventListener('push', function(event) {  console.log('Push message received', event);

  event.waitUntil(    // show notification    self.registration.showNotification(title, description));});

// event when self.addEventListener('notificationclick', function(event) {  // close notification popup  event.notification.close();

  // process notification things  event.waitUntil(doPushNotification(event));});

58

Page 59: Service Worker 201 (en)

Simple Push Demo

59

Page 60: Service Worker 201 (en)

Thank you!

60

Page 61: Service Worker 201 (en)

Special thanks to

61