我有一个Create React APP应用程序,当用户点击没有身份验证标头的应用程序网址(例如https://myapp/)时,该应用程序将重定向到身份验证流程。我可以使一切正常工作,只是一旦服务人员处于活动状态,就会从身份验证流重定向到https://myapp/
而不是导航到https://myapp/service-worker.js
。
默认的CRA workbox-sw设置不适用于此设置(因为默认情况下不包括凭据,并且未将重定向设置为follow
或manual
),所以我创建了自己的自定义服务-工人。我尝试了多种不同的显式路由至白名单和黑名单的方法,其中大多数导致浏览器拒绝显示损坏的页面(重定向响应,而RedirectMode不“关注”)。我最后的“可行”解决方案是尽可能减少干扰:
if ('function' === typeof importScripts) {
importScripts(
'https://storage.googleapis.com/workbox-cdn/releases/3.5.0/workbox-sw.js'
);
/* global workbox */
if (workbox) {
/* injection point for manifest files. */
workbox.precaching.precacheAndRoute([]);
workbox.routing.registerRoute(
/\.(?:png|gif|jpg|jpeg|webp|svg|ico)$/,
new workbox.strategies.CacheFirst({
cacheName: 'images',
plugins: [
new workbox.expiration.Plugin({
maxEntries: 60,
maxAgeSeconds: 30 * 24 * 60 * 60 // 30 Days
})
]
})
);
workbox.routing.registerRoute(
/^https:\/\/myapp\/api\/latest\/\w*\/?$/,
new workbox.strategies.StaleWhileRevalidate({
cacheName: 'apiRequests',
fetchOptions: {
credentials: 'include'
},
plugins: [
// only cache for 1 year
new workbox.expiration.Plugin({
maxAgeSeconds: 60 * 60 * 24
})
]
})
);
} else {
console.log('Workbox could not be loaded. No Offline support');
}
}
这样做的结果是,我返回站点并登录后最终在浏览器中看到了service-worker.js。我本希望希望看到我的index.html ...我尝试重命名service-worker.js
来测试这绝对是事实,它是服务工作者而不是相关的文件名-它是瑞士这使我认为这与服务人员的生命周期有关,但这并不是预期的结果!
我已经对此进行了破解,但是这种破解使我感到难过,所以我们将不胜感激!
这是黑客:
//service-worker.js
const cleanResponse = async({
url,
event,
params
}) => {
try {
// By default the service worker is being navigated to, so we need to force it here
if (/service-worker-custom.js$/.test(url)) {
return fetch(
new Request('/index.html', {
redirect: 'manual',
credentials: 'include'
})
);
}
return fetch(
new Request(event.request, {
redirect: 'manual',
credentials: 'include'
})
);
} catch (err) {
return fetch(new Request('/index.html'));
}
};
// Always go to network for navigation
// By default the service worker is being navigated to, so we need to force it here
workbox.routing.registerRoute(
({
event
}) => event.request.mode === 'navigate',
cleanResponse
);
然后在我的应用程序中,我必须清除导航