如何向 Workbox 添加提取选项?
How to add fetch options to Workbox?
我需要将 credentials: 'same-origin'
添加到所有提取请求,以便使 PWA 在受密码保护的网站中工作。否则,如果我离开网站稍后再回来,浏览器不会询问我的密码并且 returns 一个未经授权的错误。
如何使用 Workbox 做到这一点?我注意到 RequestWrapper
class 包含 fetchOptions,但我找不到使用它们的方法。
在 v2 中,预缓存应该 already set credentials: 'same-origin'
作为所有传出请求的 FetchOptions
。
对于运行时缓存,您可以通过构建自己的 RequestWrapper
实例并将其传递给您正在使用的运行时缓存处理程序来获得此行为:
const requestWrapper = new RequestWrapper({
cacheName: 'my-cache-name', // Change this for each separate cache.
fetchOptions: {
credentials: 'same-origin',
},
plugins: [], // Add any plugins you need here, e.g. CacheExpiration.
});
const staleWhileRevalidateHandler = new StaleWhileRevalidate({requestWrapper});
workboxSW.router.registerRoute(
new RegExp('/path/prefix'),
staleWhileRevalidateHandler
);
(我不确定您是如何使用 Workbox 库的,但您可能需要显式导入其他脚本才能访问 RequestWrapper
class,例如 https://unpkg.com/workbox-runtime-caching@2.0.3/build/importScripts/workbox-runtime-caching.prod.v2.0.3.js)
感谢 Jess Posnick 的回答。
为了避免重写所有工作箱策略,我最终使用了一个自定义插件:
const addFetchOptionsPlugin = {
requestWillFetch: ({ request }) => new Request(request, {
credentials: 'same-origin', redirect: 'follow'
})
};
workbox.router.registerRoute(
new RegExp('my-route'),
workbox.strategies.cacheFirst({
cacheName: 'my-cache',
plugins: [addFetchOptionsPlugin]
})
);
我需要将 credentials: 'same-origin'
添加到所有提取请求,以便使 PWA 在受密码保护的网站中工作。否则,如果我离开网站稍后再回来,浏览器不会询问我的密码并且 returns 一个未经授权的错误。
如何使用 Workbox 做到这一点?我注意到 RequestWrapper
class 包含 fetchOptions,但我找不到使用它们的方法。
在 v2 中,预缓存应该 already set credentials: 'same-origin'
作为所有传出请求的 FetchOptions
。
对于运行时缓存,您可以通过构建自己的 RequestWrapper
实例并将其传递给您正在使用的运行时缓存处理程序来获得此行为:
const requestWrapper = new RequestWrapper({
cacheName: 'my-cache-name', // Change this for each separate cache.
fetchOptions: {
credentials: 'same-origin',
},
plugins: [], // Add any plugins you need here, e.g. CacheExpiration.
});
const staleWhileRevalidateHandler = new StaleWhileRevalidate({requestWrapper});
workboxSW.router.registerRoute(
new RegExp('/path/prefix'),
staleWhileRevalidateHandler
);
(我不确定您是如何使用 Workbox 库的,但您可能需要显式导入其他脚本才能访问 RequestWrapper
class,例如 https://unpkg.com/workbox-runtime-caching@2.0.3/build/importScripts/workbox-runtime-caching.prod.v2.0.3.js)
感谢 Jess Posnick 的回答。 为了避免重写所有工作箱策略,我最终使用了一个自定义插件:
const addFetchOptionsPlugin = {
requestWillFetch: ({ request }) => new Request(request, {
credentials: 'same-origin', redirect: 'follow'
})
};
workbox.router.registerRoute(
new RegExp('my-route'),
workbox.strategies.cacheFirst({
cacheName: 'my-cache',
plugins: [addFetchOptionsPlugin]
})
);