Setting service worker to exclude certain urls only

前端 未结 5 883
遥遥无期
遥遥无期 2020-12-05 07:26

I built an app using create react which by default includes a service worker. I want the app to be run anytime someone enters the given url except when they go to /blog/, wh

相关标签:
5条回答
  • 2020-12-05 07:33

    If you are using or willing to use customize-cra, the solution is quite straight-forward.

    Put this in your config-overrides.js:

    const { adjustWorkbox, override } = require("customize-cra");
    
    module.exports = override(
      adjustWorkbox(wb => 
        Object.assign(wb, {
          navigateFallbackWhitelist: [
            ...(wb.navigateFallbackWhitelist || []),
            /^\/blog(\/.*)?/,
          ],
         })
       )
    );
    

    Note that in the newest workbox documentation, the option is called navigateFallbackAllowlist instead of navigateFallbackWhitelist. So, depending on the version of CRA/workbox you use, you might need to change the option name.

    The regexp /^/blog(/.*)?/ matches /blog, /blog/, /blog/abc123 etc.

    0 讨论(0)
  • 2020-12-05 07:38

    Another way to blacklist URLs, i.e., exclude them from being served from cache, when you're using Workbox can be achieved with workbox.routing.registerNavigationRoute:

    workbox.routing.registerNavigationRoute("/index.html", {
      blacklist: [/^\/api/,/^\/admin/],
    });
    

    The example above demonstrates this for a SPA where all routes are cached and mapped into index.html except for any URL starting with /api or /admin.

    0 讨论(0)
  • 2020-12-05 07:43

    Try using the sw-precache library to overwrite the current service-worker.js file that is running the cache strategy. The most important part is setting up the config file (i will paste the one I used with create-react-app below).

    1. Install yarn sw-precache
    2. Create and specify the config file which indicates which URLs to not cache
    3. modify the build script command to make sure sw-precache runs and overwrites the default service-worker.js file in the build output directory

    I named my config file sw-precache-config.js is and specified it in build script command in package.json. Contents of the file are below. The part to pay particular attention to is the runtimeCaching key/option. "build": "NODE_ENV=development react-scripts build && sw-precache --config=sw-precache-config.js"

    CONFIG FILE: sw-precache-config.js

    module.exports = {
        staticFileGlobs: [
            'build/*.html',
            'build/manifest.json',
            'build/static/**/!(*map*)',
        ],
        staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
        swFilePath: './build/service-worker.js',
        stripPrefix: 'build/',
        runtimeCaching: [
            {
                urlPattern: /dont_cache_me1/,
                handler: 'networkOnly'
            }, {
                urlPattern: /dont_cache_me2/,
                handler: 'networkOnly'
            }
        ]
    }
    
    0 讨论(0)
  • 2020-12-05 07:47

    here's whats working for us in the latest CRA version:

    // serviceWorker.js
    
    window.addEventListener('load', () => {
      if (isAdminRoute()) {
        console.info('unregistering service worker for admin route')
        unregister()
        console.info('reloading')
        window.location.reload()
        return false
      }
    

    we exclude all routes under /admin from the server worker, since we are using a different app for our admin area. you can change it of course for anything you like, here's our function in the bottom of the file:

    function isAdminRoute() {
      return window.location.pathname.startsWith('/admin')
    }
    
    0 讨论(0)
  • 2020-12-05 07:53

    So, considering, you have not posted any code relevant to the service worker, you might consider adding a simple if conditional inside the code block for fetch

    This code block should already be there inside your service worker.Just add the conditionals

    self.addEventListener( 'fetch', function ( event ) {
    
        if ( event.request.url.match( '^.*(\/blog\/).*$' ) ) {
            return false;
        }
         // OR
    
        if ( event.request.url.indexOf( '/blog/' ) !== -1 ) {
            return false;
        }
        //    **** rest of your service worker code ****
    

    note you can either use the regex or the prototype method indexOf. per your whim.

    the above would direct your service worker, to just do nothing when the url matches /blog/

    0 讨论(0)
提交回复
热议问题