More Related Content Similar to Service Workers Similar to Service Workers (20) More from Takenori Nakagawa More from Takenori Nakagawa (20) Service Workers7. Demo
π = 4 × arctan1 を利用して π の値を求める。
http://dev.ww24.jp/javascript/PI/
13. Web の PUSH 通知事情
今までも Notification API を使う事で、通知は可能。
WebSocket 等でリアルタイム通信を行い、
Notification API でネイティブのような通知を発行。
16. ① 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);
});
18. ② push.js
const 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);
});
19. ③ 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);
});
20. ④ service_worker.js
self.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);
});
22. 参考
・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/