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
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:
Read more on Custom responses to requests (MDN):