skip to Main Content

I’m trying to understand Service Workers, so I started from simple example

<!-- index.html -->

<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <script defer type="module" src="index.js"></script>
        <title>Document</title>
    </head>
    <body>
        <div>
            Hello, my dear!
        </div>
    </body>
</html>
// index.js

const registerServiceWorker = async () => {
    const registration = await navigator.serviceWorker.register('service-worker.js', {
        scope: './'
    });
};

await registerServiceWorker();

const response = await fetch('https://v1.cdqnpk.net/videvo_files/audio/premium/audio0137/watermarked/MusicComedyThe CTE02_96.3_preview.mp3');

console.log(response);
// service-worker.js

self.addEventListener('fetch', event => {
    event.preventDefault();

    event.respondWith(new Response(JSON.stringify({text: 'test test test'}), {
        headers: {
            'Content-Type': 'application/json'
        }
    }))
})

But I can’t get data in console like usual JSON responses instead of it JSON rendering instead of whole my document

P.S. The link in fetch is broken to get error. The original link (it is mp3 file if you follow the link the file will start download)

2

Answers


  1. 
    const response = await fetch('https://v1.cdqnpk.net/videvo_files/audio/premium/audio0137/watermarked/MusicComedyThe CTE02_96.3_preview.mp3');
    
    console.log(await response.json())
    
    Login or Signup to reply.
  2. So, if I understand it correctly, the fetch event listeners replaces global fetch handler, which is used also for getting the html page. In sample you provided you add respondWith to response with {text: 'test test test'} with no regard to where the request comes from.

    You can see the difference if you would check for the request url in your service worked event listener, for example:

    // service-worker.js
    
    self.addEventListener("fetch", (event) => {
    
      if (
        event.request.url ===
        "https://v1.cdqnpk.net/videvo_files/audio/premium/audio0137/watermarked/MusicComedyThe CTE02_96.3_preview.mp3"
      )
        event.respondWith(
          new Response(JSON.stringify({ text: "test test test" }), {
            headers: {
              "Content-Type": "application/json",
            },
          })
        );
    });
    

    Read more on Custom responses to requests (MDN):

    1. A fetch event fires every time any resource controlled by a service worker is fetched, which includes the documents inside the specified scope, and any resources referenced in those documents (for example if index.html makes a cross-origin request to embed an image, that still goes through its service worker.)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search