Service Worker はワーカー コンテキストで実行され、DOM にアクセスできないようです。ただし、Service Worker をインストールしたら、アプリがオフラインで動作することをユーザーに知らせたいと思います。どうやってやるの?
1498 次
2 に答える
6
Service Worker が にいるときはactivated state
、トースト ' Content is cached for offline use
' を表示する絶好の機会です。Service Worker を登録する際に、以下のコードを試してください。
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js').then(function(reg) {
// updatefound is fired if service-worker.js changes.
reg.onupdatefound = function() {
var installingWorker = reg.installing;
installingWorker.onstatechange = function() {
switch (installingWorker.state) {
case 'installed':
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and the fresh content will
// have been added to the cache.
// It's the perfect time to display a "New content is available; please refresh."
// message in the page's interface.
console.log('New or updated content is available.');
} else {
// At this point, everything has been precached.
// It's the perfect time to display a "Content is cached for offline use." message.
console.log('Content is now available offline!');
}
break;
case 'redundant':
console.error('The installing service worker became redundant.');
break;
}
};
};
}).catch(function(e) {
console.error('Error during service worker registration:', e);
});
}
于 2016-06-08T06:27:49.813 に答える
2
上記の@Prototype Chainの回答をテストした後、named functions
ネストさanonymous functions
れたイベントハンドラーとは対照的に、コードを自分の好みで見やすくし、後で/他の人にとって理解しやすくしたいと考えました。
しかし、ドキュメントの並べ替えに時間を費やして初めて、正しいオブジェクトで正しいイベントをリッスンすることができました。したがって、退屈なプロセスから他の誰かを救うことを期待して、ここで私の作業例を共有します。
// make sure that Service Workers are supported.
if (navigator.serviceWorker) {
navigator.serviceWorker.register('/sw.js')
.then(function (registration) {
console.log("ServiceWorker registered");
// updatefound event is fired if sw.js changed
registration.onupdatefound = swUpdated;
}).catch(function (e) {
console.log("Failed to register ServiceWorker", e);
})
}
function swUpdated(e) {
console.log('swUpdated');
// get the SW which being installed
var sw = e.target.installing;
// listen for installation stage changes
sw.onstatechange = swInstallationStateChanged;
}
function swInstallationStateChanged(e) {
// get the SW which being installed
var sw = e.target;
console.log('swInstallationStateChanged: ' + sw.state);
if (sw.state == 'installed') {
// is any sw already installed? This function will run 'before' 'SW's activate' handler, so we are checking for any previous sw, not this one.
if (navigator.serviceWorker.controller) {
console.log('Content has updated!');
} else {
console.log('Content is now available offline!');
}
}
if (sw.state == 'activated') {
// new|updated SW is now activated.
console.log('SW is activated!');
}
}
于 2017-01-29T00:16:41.483 に答える