Service Worker testing
Posted connie313
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Service Worker testing相关的知识,希望对你有一定的参考价值。
离线, 截获请求
/serviceworker
-/index.html
-/index.js
-/sw.js
index.html ==
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="hello">hello</div>
<script type="module">
console.log(412333);
let url = `http://localhost:3000/tt`;
setTimeout(()=>{
fetch(url,{method: ‘GET‘}).then(res=>{
console.log(12333, res);
document.getElementById(‘hello‘).innerHTML = "1"+JSON.stringify(res);
});
}, 3000);
setInterval(()=>{
fetch(url,{method: ‘GET‘}).then(res=>{
console.log(12333, res);
document.getElementById(‘hello‘).innerHTML = document.getElementById(‘hello‘).innerHTML+JSON.stringify(res);
});
}, 5000);
if(‘serviceWorker‘ in navigator){
window.addEventListener(‘load‘, ()=>{
navigator.serviceWorker.register(‘/sw.js‘, {scope: ‘/‘})
.then(()=>{
console.log(‘service worker register success!‘);
})
.catch(err=>{
console.log(‘service worker registration error‘);
})
})
}
</script>
</body>
</html>
---sw.js
const version = ‘0.0.1‘;
const cachekey = ‘connie-cache‘;
const self = this;
this.addEventListener(‘install‘, function(event){
event.waitUntil(
caches.open(cachekey)
.then(cache=>{
return cache.addAll([‘/‘, ‘/index.html‘])
})
);
})
this.addEventListener(‘activate‘, function(event){
console.log(‘activate‘);
event.waitUntil(
Promise.all([
// update client
// self.ClientRectList.claim(),
// clear old version
caches.keys().then(cacheList=>{
return Promise.all(cacheList.map(cacheName=>{
if(cacheName!==cachekey){
return caches.delete(cacheName);
}
}))
})
])
);
})
this.addEventListener(‘fetch‘, (event)=>{
console.log(‘fetch‘);
event.respondWith(
caches.match(event.request)
.then((response) => {
console.log(‘get fetch‘);
// 如果 service worker有自己的放回,就直接返回,减少一次http请求
if (response) {
return response;
}
// 如果service worker没有返回,那就直接请求真实远程服务
var request = event.request.clone();
return fetch(request)
.then((res) => {
console.log(res, 8888);
// 请求失败,直接返回失败的结果
if (!res || res.status !== 200) {
return res;
}
// 请求成功的话,将请求缓存起来
var respondClone = res.clone;
caches
.open(cachekey)
.then((cache) => {
cache.put(event.request, respondClone)
})
return res;
})
})
)
})
this.addEventListener(‘push‘, function(event){
console.log(‘push‘);
const title = ‘push work‘;
event.waitUntil(self.ServiceWorkerRegistration.showNotifaction(title))
});
以上是关于Service Worker testing的主要内容,如果未能解决你的问题,请参考以下文章