Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exclude index.html from serviceworker.js caching #7121

Closed
dunky11 opened this issue May 28, 2019 · 4 comments
Closed

Exclude index.html from serviceworker.js caching #7121

dunky11 opened this issue May 28, 2019 · 4 comments

Comments

@dunky11
Copy link

dunky11 commented May 28, 2019

This is maybe slightly off-topic, but I'm currently going crazy over this and cannot find any help on google.
I have read https://developers.google.com/web/fundamentals/primers/service-workers/ but their structure is quite different.

I'm trying to exclude caching of index.html from the service worker. I don't care about offline usage.
I have ejected create-react-app half a year ago, but have changed nothing in my serviceworker.js file.
My serviceWorker.js:

const isLocalhost = Boolean(
  window.location.hostname === "localhost" ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === "[::1]" ||
    // 127.0.0.1/8 is considered localhost for IPv4.
    window.location.hostname.match(
      /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    )
);

export function register(config) {
  if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
    const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
    if (publicUrl.origin !== window.location.origin) {
      return;
    }

    window.addEventListener("load", () => {
      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
      if (isLocalhost) {
        checkValidServiceWorker(swUrl, config);
        navigator.serviceWorker.ready.then(() => {
          console.log(
            "This web app is being served cache-first by a service " +
              "worker. To learn more, visit http://bit.ly/CRA-PWA"
          );
        });
      } else {
        registerValidSW(swUrl, config);
      }
    });
  }
}

function registerValidSW(swUrl, config) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        if (installingWorker == null) {
          return;
        }
        installingWorker.onstatechange = () => {
          if (installingWorker.state === "installed") {
            if (navigator.serviceWorker.controller) {
              console.log(
                "New content is available and will be used when all " +
                  "tabs for this page are closed. See http://bit.ly/CRA-PWA."
              );
              if (config && config.onUpdate) {
                config.onUpdate(registration);
              }
            } else {
              console.log("Content is cached for offline use.");
              if (config && config.onSuccess) {
                config.onSuccess(registration);
              }
            }
          }
        };
      };
    })
    .catch(error => {
      console.error("Error during service worker registration:", error);
    });
}

function checkValidServiceWorker(swUrl, config) {
  fetch(swUrl)
    .then(response => {
      const contentType = response.headers.get("content-type");
      if (
        response.status === 404 ||
        (contentType != null && contentType.indexOf("javascript") === -1)
      ) {
        navigator.serviceWorker.ready.then(registration => {
          registration.unregister().then(() => {
            window.location.reload();
          });
        });
      } else {
        registerValidSW(swUrl, config);
      }
    })
    .catch(() => {
      console.log(
        "No internet connection found. App is running in offline mode."
      );
    });
}

export function unregister() {
  if ("serviceWorker" in navigator) {
    navigator.serviceWorker.ready.then(registration => {
      registration.unregister();
    });
  }
}

Thanks for any help in advance!

@miraage
Copy link

miraage commented May 28, 2019

What's the contents of the generated service-worker.js file?

@dunky11
Copy link
Author

dunky11 commented May 28, 2019

content of https://my-website.com/service-worker.js

 importScripts("https://storage.googleapis.com/workbox-cdn/releases/3.6.3/workbox-sw.js");
 
 importScripts(
   "/precache-manifest.ac9fd9dd32e366a33425e65753b6e947.js"
 );
 
 workbox.clientsClaim();
 
 self.__precacheManifest = [].concat(self.__precacheManifest || []);
 workbox.precaching.suppressWarnings();
 workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
 
 workbox.routing.registerNavigationRoute("/index.html", {
   
   blacklist: [/^\/_/,/\/[^\/]+\.[^\/]+$/],
 });

@dunky11
Copy link
Author

dunky11 commented May 28, 2019

My /precache-manifest.ac9fd9dd32e366a33425e65753b6e947.js actually contains the entry:

  {
    "revision": "c9e0f97dc7ea2aff1d4cf8354a4bfbd6",
    "url": "/index.html"
  }

I tried deleting

workbox.routing.registerNavigationRoute("/index.html", {
   blacklist: [/^\/_/,/\/[^\/]+\.[^\/]+$/],
 });`

From serviceworker.js, but that didn't solve the issue

@dunky11
Copy link
Author

dunky11 commented May 29, 2019

Found a solution (only works if you have ejected):

You can go into /config/webpack.config.js and change the default arguments for GenerateSW() to the following:

new WorkboxWebpackPlugin.GenerateSW({
          clientsClaim: true,
          exclude: [/\.map$/, /asset-manifest\.json$/, /index.html/],
          importWorkboxFrom: "cdn",
          navigateFallbackBlacklist: [
            // Exclude URLs starting with /_, as they're likely an API call
            new RegExp("^/_"),
            // Exclude URLs containing a dot, as they're likely a resource in
            // public/ and not a SPA route
            new RegExp("/[^/]+\\.[^/]+$")
          ]

I will close this, thank you anyways!

@dunky11 dunky11 closed this as completed May 29, 2019
@lock lock bot locked and limited conversation to collaborators Jun 3, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants