Service Workers
-
Upload
takenori-nakagawa -
Category
Technology
-
view
541 -
download
0
Transcript of Service Workers
Demo
π = 4 × arctan1 を利用して π の値を求める。
http://dev.ww24.jp/javascript/PI/
Service Workers で出来る事
・Cache
ApplicationCache よりも高度なキャッシュ機能
・Push
PUSH 通知
・Sync 指定した任意のタイミングで起動
http://www.w3.org/TR/service-workers/
Web の PUSH 通知事情
今までも Notification API を使う事で、通知は可能。
WebSocket 等でリアルタイム通信を行い、Notification API でネイティブのような通知を発行。
Service Worker
WorkerWorker を登録
http://www.html5rocks.com/ja/tutorials/service-worker/introduction/
①
① register.js
navigator.serviceWorker.register("/service_worker.js", { scope: "./" }).then(function (serviceWorkerRegistration) { // PUSH 通知を購読情報の取得 return serviceWorkerRegistration.pushManager.getSubscription(); }).then(function (subscription) { if (subscription) { console.log("subscription:", subscription.subscriptionId); }
// PUSH 通知を購読していない場合に購読 (Permission が求められる) return serviceWorkerRegistration.pushManager.subscribe(); }).then(function (subscription) { console.log("subscription:", subscription.subscriptionId); }).catch(function (err) { console.error(err); });
Service Worker
GCM
Server
Google Cloud Messaging
Chrome の場合
イベント通知
イベント通知
データ取得イベント通知
スマホ等のブラウザ
②③
④
② push.jsconst API_END_POINT = "https://android.googleapis.com/gcm/send";
request.post({ url: API_END_POINT, headers: { Authorization: "key=" + GCM_API_KEY }, json: true, body: { registration_ids: registration_ids } }, function (err, req, data) { if (req.statusCode !== 200) { return callback && callback(err || new Error("status:" + req.statusCode)); } callback && callback(err, data); });
③ service_worker.js
self.addEventListener("push", function (event) { // GCM から PUSH イベントが呼ばれる
var notification = self.registration.showNotification("YO!", { body: "Hello Service Workers Push!", icon: "/img/html5-badge.png", tag: "hello-service-workers" });
event.waitUntil(notification); });
④ service_worker.jsself.addEventListener("push", function (event) { // fetch を使って通知データを取得 var promise = self.fetch("https://example.com/api/data", { credentials: "include" }).then(function (res) { return res.text(); }).then(function (text) { var data = JSON.parse(text);
return self.registration.showNotification(data.title, { body: data.body, icon: icon_path, tag: "hello-service-workers" }); });
event.waitUntil(promise); });
参考
・Push Notifications on the Open Web
http://updates.html5rocks.com/2015/03/push-notificatons-on-the-open-web
・ServiceWorker API - Web API インターフェイス | MDN
https://developer.mozilla.org/ja/docs/Web/API/ServiceWorker_API
・Is ServiceWorker ready?
https://jakearchibald.github.io/isserviceworkerready/