1

Here is my code. Both index.html and service-worker.js are served on http://localhost:8080.

index.html

<!doctype html>
<html lang="zh">
  <head>
    <script>
      if ("serviceWorker" in navigator) {
        navigator.serviceWorker.register("/service-worker.js", {
          scope: "/",
          // scope: "http://localhost:9999/"
        });
      }
    </script>
  </head>
  <body>
    <button id="sendApiRequest">send cors-request</button>
    <script>
       document.querySelector("#sendApiRequest").addEventListener("click", () => {
          const API = "http://localhost:9999/api/data";
          fetch(API);
       });
    </script>
  </body>
</html>

service-worker.js

self.addEventListener("fetch", (event) => {
  console.log("fetch event fired", event.request.url);
});

Below is my simulated server-side API code which served on http://localhost:9999

// Mock API server with NodeJs

const http = require('http');

const server = http.createServer((req, res) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  const data = {
    msg: 'success',
    time: new Date().toLocaleString(),
  }
  res.end(JSON.stringify(data));
});

const port = 9999;
server.listen(port, () => {
  console.log(`backend api on http://localhost:${port}`);
});

When I click the send request button, the fetch event in service-worker.js is not triggered. What is the problem? And how should I intercept CORS requests in the service worker?

7
  • 1
    How do you know it's not triggered? Are there any errors in your console? What does your dev tools network tab show? Commented yesterday
  • Where is self defined? Commented yesterday
  • I am not able to reproduce the problem. The service worker loads and works as expected using the supplied code on http://localhost:8080 and http://localhost:9999. The fetch event fires and the api returns json. The problem seems specific to your test environment. And the console and network panels in developer tools should help you identify it. Commented yesterday
  • @Yogi console.log("fetch event fired", event.request.url); the console panels in developer tools does not output log. Commented yesterday
  • 1
    @Yogi Thank you very much, I have found the problem. Closing and reopening the page makes the service worker take effect. Then refreshing the page makes the resources use the service worker instead of the network (note that you cannot force a refresh, because it will make a network request). Commented yesterday

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.