我想了解 Service Workers,所以我从简单的示例开始
<!-- 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'
}
}))
})
但是我无法像往常一样在
console
中获取数据 JSON
响应而不是它 JSON
渲染而不是整个文档
附注
fetch
中的链接已损坏并出现错误。 原始链接(这是mp3文件,如果您点击链接,文件将开始下载)
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())