如何使用create-react-app制作“自定义脱机后备”页面?

时间:2018-09-23 11:52:16

标签: reactjs create-react-app web-worker offline-caching workbox-webpack-plugin

我想开发一个可在具有缓存的脱机页面上运行的应用程序。我正在使用工作箱并将react-app-rewired链接到生成的自定义服务工作者,以创建Create react应用程序。我已经成功地预先缓存了静态文件,并使用Network首先缓存了动态内容。但是,当我要在访问未缓存的页面时使应用程序显示脱机页面时,会出现空白页面。这是我的自定义代码。谁能解决我的问题?我陷入了这个问题。

R.id.ll_screenshot

这是我自定义的离线页面:

// importScripts('path/to/offline-google-analytics-import.js');
// workbox.googleAnalytics.initialize();
workbox.setConfig({ debug: true });
// See https://developers.google.com/web/tools/workbox/guides/configure-workbox
workbox.core.setLogLevel(workbox.core.LOG_LEVELS.debug);
self.addEventListener('install', event => event.waitUntil(self.skipWaiting()));
self.addEventListener('activate', event => event.waitUntil(self.clients.claim()));

// We need this in Webpack plugin (refer to swSrc option): https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin#full_injectmanifest_config
workbox.precaching.precache(self.__precacheManifest);

workbox.precaching.precache([
  {
    url: '/offline.html',
    revision:'1234',
  }
]);

workbox.precaching.addRoute();

// app-shell cahcing
workbox.routing.registerRoute("/", workbox.strategies.cacheFirst());

//fungsinya buat apa ? Cari tau dulu
workbox.routing.registerNavigationRoute('/index.html');

var networkFirst = workbox.strategies.networkFirst({
  cacheName: 'outside-pages',
  plugins: [
     new workbox.cacheableResponse.Plugin({
       statuses: [0, 200],
     })
   ]
});

const customHandler = async (args) => {
  try {
    console.log(args.event.request.url)
    const response = await networkFirst.handle(args);
    return response || await caches.match(args.event.request.url);
  }catch (error) {
      return caches.open('/offline.html').then(function(cache) {
         return caches.match('/offline.html');
    })
  }
}

workbox.routing.registerRoute(
  new RegExp('http://192.168.1.37/api/(.*)'),
  customHandler,
);

workbox.routing.setCatchHandler(({url, event, params}) => {
  console.log(event)
});

0 个答案:

没有答案