• R/O
  • HTTP
  • SSH
  • HTTPS

Tags
No Tags

Frequently used words (click to add to your profile)

javac++androidlinuxc#windowsobjective-ccocoa誰得qtpythonphprubygameguibathyscaphec計画中(planning stage)翻訳omegatframeworktwitterdomtestvb.netdirectxゲームエンジンbtronarduinopreviewer

PWAのサンプルコード


File Info

Rev. 664d482382ac0451bd083a3a14b1c3d7b3083db2
Size 2,429 bytes
Time 2019-11-29 19:35:32
Author hylom
Log Message

add sample codes

Content

// test-db.jsを読み込む
self.importScripts("./test-db.js");

// キャッシュを識別する名前を定義
const CACHE_NAME = "knowledge_push_example";

// キャッシュ対象を指定する
// 今回は index.html、index.js、test-db.js の3つ
const TARGET_URLS = [
  "index.html",
  "index.js",
  "test-db.js",
];

// installイベントハンドラを登録
self.addEventListener("install", event => {
  // 引数で指定したPromiseが解決されるまで待機
  event.waitUntil(
    // キャッシュを開く
    self.caches.open(CACHE_NAME)
      .then(cache => {
        // 指定したURLをすべてキャッシュする
        return cache.addAll(TARGET_URLS);
      })
  );
});

// fetchイベントハンドラを登録
self.addEventListener("fetch", event => {
  // オンラインかどうかをチェック
  if (self.navigator.onLine) {
    // オンラインならネットワークリクエストを行う
    event.respondWith(fetch(event.request));
    return;
  }

  // リクエストURLをチェック
  const url = new URL(event.request.url);

  // ルートへのアクセスの場合、index.htmlを返す
  let targetRequest = event.request;
  if (url.pathname == "/") {
    url.pathname = "/index.html";
    targetRequest = url.toString();
  }

  // リクエストに対するレスポンスを設定する
  event.respondWith(
    // リクエストに該当するキャッシュを探す
    self.caches.match(targetRequest, {cacheName: CACHE_NAME})
      .then(response => {
        if (response) {
          // キャッシュが存在したのでそれを返す
          return response;
        }
        // キャッシュが存在しないのでネットワークリクエストを行う
        return fetch(event.request);
      })
  );
});

// pushイベントハンドラを登録
self.addEventListener("push", event => {
  // 通知設定が行われているかをチェック
  if (!self.Notification || self.Notification.permission !== "granted") {
    // 通知設定が行われていなければ何もせず終了
    return;
  }

  // 送信されたデータを取得
  var data = {};
  if (event.data) {
    data = event.data.json();
    console.log("push notification received: " + JSON.stringify(data));

    if (data.message) {
      testDb.addMessage(data.message)
        .then(() => {
          console.log("message saved.");
        });
    }
  }
});