手动重播由workbox-background-sync排队的请求 [英] Manually replaying requests queued by workbox-background-sync

查看:150
本文介绍了手动重播由workbox-background-sync排队的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在PWA应用程序中进行脱机支持.为此,我正在使用 workbox .这是我当前的代码:

I am working on offline support in my PWA app. I am using workbox for that. This is my current code:

const addToFormPlugin = new workbox.backgroundSync.Plugin('addToForm');

workbox.routing.registerRoute(
RegExp('MY_PATH'),
  workbox.strategies.networkOnly({
    plugins: [addToFormPlugin]
  }),
  'POST'
);

该代码在我的计算机上似乎可以正常工作.但是,一旦我在手机上运行该应用程序,上传存储在IndexedDB中的请求就会花一些时间.我知道它发生在SYNC上,但似乎至少需要5分钟.这不是我真正需要的.我想知道是否有一个选项可以访问IndexDB并在单击时手动"发送所有请求.另一种方法是检查设备是否在线.请求的存储方式如下:

The code seems to works fine on my computer. However, once I run the app on the phone it takes ages to upload requests stored in IndexedDB. I know that it happens on the SYNC but it seems to take at least 5 minutes. This is not exactly what I need. I wonder if there is an option to access the IndexDB and send all the requests "manually" on click. Another way would be to check if the device is online. Here is how requests are stored:

推荐答案

如果您需要强制执行此操作,则最干净的方法是使用workbox.backgroundSync.Queue类(而不是workbox.backgroundSync.Plugin)直接.

If you need to force this, the cleanest approach would be to use the workbox.backgroundSync.Queue class (instead of workbox.backgroundSync.Plugin) directly.

Plugin 设置 fetchDidFail回调 a>,因此,如果您使用Queue类,则需要自己执行以下操作:

The Plugin class takes care of setting up a fetchDidFail callback for you, so if you use the Queue class, you need to do that yourself:

const queue = new workbox.backgroundSync.Queue('addToForm');

workbox.routing.registerRoute(
  RegExp('MY_PATH'),
  workbox.strategies.networkOnly({
    plugins: [{
      fetchDidFail: async ({request}) => {
        await queue.addRequest(request);
      },
    }],
  }),
  'POST'
);

然后您可以调用 以触发重播,例如,由于message事件:

You could then call queue.replayRequests() to trigger the replay, e.g., as a result of a message event:

self.addEventListener('message', (event) => {
  if (event.data === 'replayRequests') {
    queue.replayRequests();
  }
});

但是...总而言之,我认为您最好的选择是让浏览器执行其任务",并弄清楚何时是重播排队请求的正确时间.最终将使移动设备对电池更友好.

But... that all being said, I think your best bet is just to let the browser "do its thing" and figure out when the right time is to replay the queued requests. That will end up being more battery-friendly for mobile devices.

如果您对触发sync事件之前浏览器等待的间隔感到不满意,那么最好的做法是针对浏览器打开一个错误-无论是

If you're unhappy with the interval that the browser waits before firing a sync event, then the best course of action could be to open a bug against the browser—whether it's Chrome (as appears in your screenshot) or another browser.

这篇关于手动重播由workbox-background-sync排队的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆