我最近从Workbox 3.5.0迁移到Workbox 5.1.2
我正在通过CDN使用Workbox SW
importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js');我已经更新了我的服务工作者文件以使用最新的插件类,并适当地重命名了这些类-一切都运行得很好!
我遇到的唯一真正的问题/困惑是backgroundSync模块。我已经通读了文档,并在Stackoverflow和Google上搜索了解决方案/建议,但找不到任何明确回答我问题的东西。
我正在尝试将失败的请求添加到一个队列中,一旦网络恢复,这些请求将被重试。
workbox.routing.registerRoute(new RegExp('/\/php\/postPO.php/'),
new workbox.strategies.NetworkOnly({
plugins: [
new workbox.backgroundSync.BackgroundSyncPlugin('po-data-queue', {
maxRetentionTime: 24 * 60 * 2
})
]
}),
'POST'
);
const queue = new workbox.backgroundSync.Queue('po-data-queue-2');
self.addEventListener('fetch', (event) => {
const promiseChain = fetch(event.request.clone()).catch((err) => {
return queue.pushRequest({ request: event.request });
});
event.waitUntil(promiseChain);
});我知道上面的代码不起作用,因为如果我给两个队列命名相同的名称,那么就会抛出一个关于使用唯一队列名称的错误。我需要两个函数才能使用backgroundSync模块,还是只需要其中一个。另外,我是需要自己创建indexedDB,还是需要workbox来处理?在使用workbox 3.5.0时,我创建了indexedDB,并添加了失败的请求,如下所示(它工作得很好):
function createIndexedDB() {
if (!('indexedDB' in window)) {return null;}
return idb.open('pos-data-queue', 1, function(upgradeDb) {
if (!upgradeDb.objectStoreNames.contains('events')) {
const eventsOS = upgradeDb.createObjectStore('events', {keyPath: 'key', autoIncrement: true});
}
});
}
const dbPromise = createIndexedDB();
function saveEventDataLocally(events) {
console.log(events);
if (!('indexedDB' in window)) {return null;}
return dbPromise.then(db => {
const tx = db.transaction('events', 'readwrite');
const store = tx.objectStore('events');
return Promise.all(events.map(event => store.put(event)))
.catch((err) => {
console.log(err);
tx.abort();
throw Error('Events were not added to the store');
});
});
}
const bgSyncPlugin = new workbox.backgroundSync.Plugin('pos-data-queue');
const networkWithBackgroundSync = new workbox.strategies.NetworkOnly({
plugins: [bgSyncPlugin],
});
workbox.routing.registerRoute(
/\/php\/postPO.php/,
networkWithBackgroundSync,
'POST'
);我不能理解这是如何工作的,任何帮助都将不胜感激
发布于 2020-06-25 13:32:32
您不需要同时使用BackgroundSyncPlugin和Queue。每个实例都需要唯一的名称。IndexedDB条目由工作箱本身管理。
在您的代码示例中,我在注册BackgroundSyncPlugin时看到了一个可疑的空格(使正则表达式无效
workbox.routing.registerRoute(new RegExp(' /\/php\/postPO.php/'),
^也许你可以尝试一下:
workbox.routing.registerRoute(/\/php\/postPO\.php/,
new workbox.strategies.NetworkOnly({
plugins: [
new workbox.backgroundSync.BackgroundSyncPlugin('po-data-queue', {
maxRetentionTime: 2 * 24 * 60 // two days
})
]
}),
'POST'
);上面的方法适用于任何包含/php/postPO.php的网址。你可以在here上测试它。
官方文档here展示了一些示例,以及如何测试后台同步是否正常工作。
https://stackoverflow.com/questions/62557881
复制相似问题