在我的服务工作者中,我正在实现后台同步与工作框,如下所示
workbox.routing.registerRoute(
options => options.url.pathname.startsWith('/api/'),
new workbox.strategies.NetworkOnly({
plugins: [
new workbox.backgroundSync.Plugin('myQueueName', {
maxRetentionTime: 14 * 24 * 60,
onSync() {
showNotification('background sync ran.');
}
})]
}),
'POST'
);当我通过禁用网络访问、执行请求然后打开网络访问来测试该行为时,我看到的是在showNotification中触发的通知,但我没有看到实际的请求。
奇怪的是,当我删除onSync回调时,我现在看到的是请求,但显然,我没有创建任何通知。我如何才能得到一个回调,并让实际的请求重放?
发布于 2020-02-07 16:59:53
我查看了workbox的实现,发现了以下代码:
class Queue {
...
constructor(name, {onSync, maxRetentionTime} = {}) {
...
this._onSync = onSync || this.replayRequests;
... 再往下走
_addSyncListener() {
if ('sync' in registration) {
self.addEventListener('sync', (event) => {
...
const syncComplete = async () => {
this._syncInProgress = true;
let syncError;
try {
await this._onSync({queue: this});因此,当您不传递onSync回调时,默认情况是调用replayRequests。如果你通过了一个,你必须自己做,例如:
workbox.routing.registerRoute(
options => options.url.pathname.startsWith('/api/'),
new workbox.strategies.NetworkOnly({
plugins: [
new workbox.backgroundSync.Plugin('myQueueName', {
maxRetentionTime: 14 * 24 * 60,
onSync({ queue }) {
// !!! important call here !!!
queue.replayRequests();
showNotification('background sync ran.');
}
})]
}),
'POST'
);https://stackoverflow.com/questions/60117924
复制相似问题