码迷,mamicode.com
首页 > 其他好文 > 详细

Service Worker testing

时间:2020-10-26 11:17:19      阅读:19      评论:0      收藏:0      [点我收藏+]

标签:ring   ==   wait   his   map   open   rect   返回   status   

离线, 截获请求

/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

标签:ring   ==   wait   his   map   open   rect   返回   status   

原文地址:https://www.cnblogs.com/connie313/p/13873567.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!