我正在尝试创建一个支持脱机发布请求的Web应用程序。我使用工作箱预缓存了我的文件,但是插件Background Sync不起作用。我没有看到使用Chrome Dev Tools在IndexedDB中排队的请求。如何运作?
答案 0 :(得分:0)
在Service Worker文件中:
importScripts('https://storage.googleapis.com/workbox-cdn/releases/4.2.0/workbox-sw.js');
//The new installed service worker replaces the old service worker immediately
self.skipWaiting();
//Test workbox
if (workbox) {
console.log('Workbox is loaded');
} else {
console.log('Workbox did not loaded');
}
//Precaching
workbox.precaching.precacheAndRoute([
{ url: 'index.html', revision: '0000' },
{ url: 'manifest.json', revision: '0000' },
{ url: 'images/icons/icon-48x48.png', revision: '0000' },
]);
//BackgroundSync
//On https://ptsv2.com/t/n5y9f-1556037444 you can check for received posts
const bgSyncPlugin = new workbox.backgroundSync.Plugin('queue', {
maxRetentionTime: 24 * 60 // Retry for max of 24 Hours
});
workbox.routing.registerRoute(
'https://ptsv2.com/t/n5y9f-1556037444/post',
new workbox.strategies.NetworkOnly({
plugins: [bgSyncPlugin]
}),
'POST'
);
在index.html中:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!--Include Manifest (Metadata for Browser)-->
<link rel="manifest" href="manifest.json">
<!--Metadata for Apple-->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Weather PWA">
<link rel="apple-touch-icon" href="images/icons/icon-144x144.png">
<!--Metadata for Microsoft-->
<meta name="msapplication-TileImage" content="images/icons/icon-144x144.png">
<meta name="msapplication-TileColor" content="#2F3BA2">
</head>
<body>
<button onclick="sendPost()">Send post</button>
<!--Register Service Worker-->
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('service-worker.js')
.then(function() { console.log('Service Worker Registered'); });
}
</script>
<!--Send the post request-->
<script>
function sendPost() {
console.log("Send post...");
fetch('https://ptsv2.com/t/n5y9f-1556037444/post', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
mode:'no-cors',
body: JSON.stringify({
message: 'hello world'
}),
}).then(function (res) {
console.log('Sended data', res);
}).catch(function (error) {
console.log('Error while sending data', error);
})
}
</script>
</body>
</html>