Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

reactjs - React PWA Service Worker works locally, but not when hosted on Netlify

I'm trying to learn more about PWA Service Workers and wanted to implement that feature on this personal project site I'm working on. When I run Google's Lighthouse on Localhost the start_url passes and responds with a 200 offline and registers a service worker.

However, when I push the changes to Github which I'm hosting on Netlify and run the same Lighthouse test, I get: start_url does not respond with a 200 when offline. Timed out waiting for start_url to respond. Does not register a service worker that controls page.

This is the script I have in the index.html:

 <!-- PWA SERVICE WORKER SCRIPT -->
  <script>
    if ('serviceWorker' in navigator) {
      window.addEventListener('load', function() {
        navigator.serviceWorker.register('worker.js').then(function(registration) {
          console.log('Worker registration successful', registration.scope);
        }, function(err) {
          console.log('Worker registration failed', err);
        }).catch(function(err) {
          console.log(err);
        });
      });
    } else {
      console.log('Service Worker is not supported by browser.');
    }
  </script>

Here is my manifest.json:

{
  "short_name": "Arc-teryx",
  "name": "Arc-teryx using Contentful/Graphql",
  "icons": [
    {
      "src": "favicon.ico",
      "sizes": "64x64 32x32 24x24 16x16",
      "type": "image/x-icon"
    },
    {
      "src": "logo192.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "logo512.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],
  "start_url": ".",
  "display": "standalone",
  "orientation": "portrait",
  "theme_color": "#000000",
  "background_color": "#ffffff"
}

Here is my worker.js file in public folder:

let CACHE_NAME = "Arc-teryx";
let urlsToCache = ["/", "/completed"];

// Install a service worker
self.addEventListener("install", (event) => {
  // Perform install steps
  event.waitUntil(
    caches.open(CACHE_NAME).then(function (cache) {
      console.log("Opened cache");
      return cache.addAll(urlsToCache);
    })
  );
});

// Cache and return requests
self.addEventListener("fetch", (event) => {
  event.respondWith(
    caches.match(event.request).then(function (response) {
      // Cache hit - return response
      if (response) {
        return response;
      }
      return fetch(event.request);
    })
  );
});

// Update a service worker
self.addEventListener("activate", (event) => {
  let cacheWhitelist = ["Arc-teryx"];
  event.waitUntil(
    caches.keys().then((cacheNames) => {
      return Promise.all(
        cacheNames.map((cacheName) => {
          if (cacheWhitelist.indexOf(cacheName) === -1) {
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

Can anyone see what I may be doing incorrectly and point me in the right direction for a fix?

Link to the Repo

Netlify link: Project

Thank you!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Amazing how I've been trying to figure this out for awhile and as soon as I post it, I figured it out 30min later.

Anyways, if this helps anyone else out there who might be having a similar issue, this was my fix.

I changed the let urlsToCache = ["/", "/completed"]; to let urlsToCache = ["/"] in the worker.js file and the "start_url": "." to "start_url": "/" in the manifest.json


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...