Javascript 脱机时创建React App ServiceWorker.js重定向
我有一个使用CreateReact应用程序创建的React应用程序。默认情况下,该工具为我们创建一个serviceworner.js文件,我正在使用该文件注册一个serviceworer。此外,这些文件建议使用google的workbox向导创建一个service-worker.js,用于管理我的网站以实现脱机目的。我的目标是将offline.html页面存储在浏览器缓存中,当没有联机连接时,呈现缓存的offline.html页面 我成功地将Javascript 脱机时创建React App ServiceWorker.js重定向,javascript,service-worker,create-react-app,Javascript,Service Worker,Create React App,我有一个使用CreateReact应用程序创建的React应用程序。默认情况下,该工具为我们创建一个serviceworner.js文件,我正在使用该文件注册一个serviceworer。此外,这些文件建议使用google的workbox向导创建一个service-worker.js,用于管理我的网站以实现脱机目的。我的目标是将offline.html页面存储在浏览器缓存中,当没有联机连接时,呈现缓存的offline.html页面 我成功地将offline.html存储在缓存中,正如您在下面看到
offline.html
存储在缓存中,正如您在下面看到的,它存储在预缓存的URL中(检查最后两行)
如果在浏览器中更改URL,我还可以手动导航到offline.html
但是,每当没有连接时,我都无法自动获取该文件并进行渲染
在从CRA为我生成的serviceWorker.js代码中,有一个名为checkValidServiceWorker
的函数:
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
const OFFLINE_URL = '/.offline/offline.html';
return caches.match(OFFLINE_URL).then((response) => {
console.log(response)
});
});
}
因此,在函数的catch
部分,我想执行重定向,因为这是我们脱机时运行的逻辑。我读了很多文档,但我当前的解决方案不起作用。关于如何在我的服务人员中重定向有什么想法吗