我正在使用Workboxv4.3.1为web应用程序的用户提供脱机功能。
虽然在Chrome中一切都很完美,但你希望PWA能正常工作(也就是说,所有的更新都是本地缓存的,应用程序的所有更新都在IndexedDB中捕获,并在应用程序恢复在线时同步回服务器)。
然而,对我来说,主要的用例是提供对iOS Safari的支持,并将其作为PWA。
使用Safari中的Service在本地缓存所有页面,并且所有脱机更新也在索引DB中捕获,如下所示,

但是,当连接联机返回时,浏览器不会触发同步事件(本例中为Safari)。虽然Safari本机不支持后台同步,但当我刷新页面时,如果SW初始化发现一些数据要刷新到索引DB中的服务器,则应该手动触发同步事件。
但是这种情况并没有发生,我试图手动侦听“消息”-- "replayRequests“,然后重放请求--这也不起作用。
这里的任何帮助都将不胜感激。这是供参考的服务工作人员代码。
// If we're not in the context of a Web Worker, then don't do anything
if ("function" === typeof importScripts) {
importScripts(
"https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js"
);
//Plugins
// Background Sync Plugin.
const bgSyncPlugin = new workbox.backgroundSync.Plugin("offlineSyncQueue", {
maxRetentionTime: 24 * 60
});
// Alternate method for creating a queue and managing the events ourselves.
const queue = new workbox.backgroundSync.Queue("offlineSyncQueue");
workbox.routing.registerRoute(
matchCb,
workbox.strategies.networkOnly({
plugins: [
{
fetchDidFail: async ({ request }) => {
await queue.addRequest(request);
}
}
]
}),
"POST"
);
// CacheKeyControlPlugin
const myCacheKeyPlugin = {
cacheKeyWillBeUsed: async ({ request, mode }) => {
normalizedUrl = removeTimeParam(request.url);
return new Request(normalizedUrl);
}
};
if (workbox) {
console.info("SW - Workbox is available and successfully installed");
} else {
console.info("SW - Workbox unavailable");
}
//Intercept all api requests
var matchCb = ({ url, event }) => {
// Filter out the presence api calls
return url.pathname.indexOf("somethingidontwanttocache") == -1;
};
function removeTimeParam(urlString) {
let url = new URL(urlString);
url.searchParams.delete("time");
return url.toString();
}
/* //Pre cache a page and see if it works offline - Temp code
workbox.precaching.precache(getPageAPIRequestURLs(), {
cleanUrls: false
}); */
workbox.routing.registerRoute(
matchCb,
new workbox.strategies.CacheFirst({
cacheName: "application-cache",
plugins: [myCacheKeyPlugin]
})
);
self.addEventListener("message", event => {
if (event.data === "replayRequests") {
queue.replayRequests();
}
});
}发布于 2019-09-10 16:26:45
当服务工作进程启动时,workbox-background-sync通过重放排队请求来模拟缺乏本机支持的浏览器中的后台同步功能。服务工作流程应该是轻量级和短暂的,并且在有一段时间没有任何事件的情况下会被猛烈地杀死,然后再次启动以响应进一步的事件。
重新加载网页可能会导致服务工作人员进程启动,前提是它以前已经停止。但是,如果服务工作人员仍然在运行,那么重新加载页面只会导致在现有进程上触发一个fetch事件。
服务工作进程在被杀死之前可以保持空闲的时间间隔是浏览器依赖的。
Chrome的DevTools提供了一种检查服务工作者状态并按需启动/停止服务的方法,但我不认为Safari的DevTools提供了这种功能。如果你想知道服务人员被停止了,然后重新启动它,我会退出Safari,重新打开它,然后导航回你的web应用程序。
https://stackoverflow.com/questions/57863098
复制相似问题