DOM

インターフェイス

ServiceWorker インターフェイス

  編集:2022.04.08 by T.A.

MS(en-US)

実験的: これは実験的な機能です。本番で使用する前にブラウザー互換性一覧表をチェックしてください。

ServiceWorker API のインターフェイスである ServiceWorker は service worker に関するレファレンスを提供しています。様々なブラウザー環境(例えばページ、worker など)が同一の service worker に関連付けることができて、一意な ServiceWorker オブジェクト​からアクセスできます。

ServiceWorker オブジェクトはプロバティ ServiceWorkerRegistration.active と ServiceWorkerContainer.controller プロパティ ― これは起動された service worker でページを管理しています(そのservice workerが正常に登録されて管理されるページがリロードされています) ― の中で利用可能です。

ServiceWorker インターフェイスへは、install や activate 、そして fetch を含む機能的なイベントといったライフ サイクル イベントのセットが送られます。ServiceWorker オブジェクトは、ライフサイクルに関係する ServiceWorker.state(状態)を持っています。

プロパティ

ServiceWorker インターフェイスは親となる Worker からプロパティを継承します。

ServiceWorker.scriptURL 読取専用
ServiceWorkerRegistration の一部と定義されたスクリプト URL にシリアライズされた ServiceWorker を返します。この URL はその ServiceWorker を登録している document と同一オリジン上でなければなりません。
ServiceWorker.state 読取専用
service worker の状態を返します。installing、installed、activating、activated、redundant のいずれかの値を返します。
メソッド

ServiceWorker インターフェイスは親であるWorkerインターフェイスからメソッドを継承していますが、Worker.terminate は例外です。このメソッドは service worker からアクセスされるべきではありません。

イベントハンドラー
ServiceWorker.onstatechange 読取専用
statechange イベントが発火した際に呼び出される EventListener プロパティです。このイベントは ServiceWorker.state が変更された際に発火されます。
このコードスニペットは service worker registration-events sample(live demo)の一部です。ServiceWorker.state のあらゆる変更をリッスンし、その値を返します。
if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('service-worker.js', {
        scope: './'
    }).then(function (registration) {
        var serviceWorker;
        if (registration.installing) {
            serviceWorker = registration.installing;
            document.querySelector('#kind').textContent = 'installing';
        } else if (registration.waiting) {
            serviceWorker = registration.waiting;
            document.querySelector('#kind').textContent = 'waiting';
        } else if (registration.active) {
            serviceWorker = registration.active;
            document.querySelector('#kind').textContent = 'active';
        }
        if (serviceWorker) {
            // logState(serviceWorker.state);
            serviceWorker.addEventListener('statechange', function (e) {
                // logState(e.target.state);
            });
        }
    }).catch (function (error) {
        // Something went wrong during registration. The service-worker.js file
        // might be unavailable or contain a syntax error.
    });
} else {
    // The current browser doesn't support service workers.
}

テスト
HTML:

ここに表示
スクリプト組み込み:



スクリプト:


スクリプト:



表示内容:
表示内容: