ServiceWorker
Experimental: これは実験的な機能です。
本番で使用する前にブラウザー互換性一覧表をチェックしてください。
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
(en-US) 読取専用-
ServiceWorkerRegistration
の一部と定義されたスクリプト URL にシリアライズされたServiceWorker
を返します。この URL はそのServiceWorker
を登録している document と同一オリジン上でなければなりません。 ServiceWorker.state
読取専用-
service worker の状態を返します。
installing
,installed
,activating
,activated
,redundant
のいずれかの値を返します。
イベントハンドラー
ServiceWorker.onstatechange
(en-US) 読取専用-
statechange
イベントが発火した際に呼び出されるEventListener
プロパティです。このイベントはServiceWorker.state
が変更された際に発火されます。
メソッド
ServiceWorker
インターフェイスは親であるWorker
インターフェイスからメソッドを継承していますが、Worker.terminate
は例外です。このメソッドは service worker からアクセスされるべきではありません。
例
このコードスニペットは 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.
}
仕様
Specification |
---|
Service Workers # serviceworker-interface |
ブラウザーの互換性
BCD tables only load in the browser