【问题标题】:Workbox background sync doesn't run if setting onSync callback如果设置 onSync 回调,Workbox 后台同步不会运行
【发布时间】:2020-02-08 00:59:53
【问题描述】:

在我的服务人员中,我正在像这样实现与工作箱的后台同步

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 回调时,我现在看到了请求,但显然,我没有创建任何通知。如何获得回调重播实际请求?

【问题讨论】:

    标签: javascript service-worker workbox background-sync


    【解决方案1】:

    我查看了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'
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-14
      • 2019-04-18
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      • 1970-01-01
      相关资源
      最近更新 更多