Service Worker 常用api,写法几乎固定

207 阅读1分钟

Service Worker

有三个事件

self.addEventListener('install',event=>{
  console.log('install',event)
})
self.addEventListener('active',event=>{
  console.log('active',event)
})
self.addEventListener('fetch',event=>{
  console.log('fetch',event)
})

event.waitUntil();要传入一个promise,promise执行完后才会激活active

event.waitUntil(self.skipWaiting())可以强制active,强制停止旧的serverWork,开始新的

cache

const CACHE_NAME = 'cache-v1'
self.addEventListener('install',event=>{
  console.log('install',event)
  event.waitUntil(caches.open(CACHE_NAME).then(cache=>{
    cache.addAll([
      '/',
      './index.css'
    ]);
  }))

 
  
})
self.addEventListener('activate',event=>{
  console.log('activate',event)
  //在activate中判断缓存是否更新
  event.waitUntil(caches.keys().then(cacheNames=>{
    return Promise.all(cacheNames.map(cacheName=>{
      if(cacheName!==CACHE_NAME){
        return caches.delete(cacheName);
      }
    }))
  }));

})
self.addEventListener('fetch',event=>{
  console.log('fetch',event)
  event.respondWith(caches.open(CACHE_NAME).then(cache=>{//respondWith需要返回一个response对象
    return cache.match(event.request).then(response=>{
      if(response){
        //response存在则说明命中了缓存
        return response;
      }
      return fetch(event.request).then(response=>{
        cache.put(event.request,response.clone())//response是流逝的,只能读取一次
        return response;
      })
    })
  }))
})

Notification Api

Notification.permission 是查看通知权限,一般是default,不答应也不拒绝,还有两个状态是granted,denied

Notification.requestPremission()弹出授权请求,返回一个promise

Notification.requestPermission().then(permission=>console.log(permission))

当Notification.permission为granted时,可以new Notification()发送通知

//第一个参数字符串,通知的title
//第二个参数是对象,{body:"通知的副标题"} 对象里面放参数,body是副标题
new Notification("a",{body:"hello"})

在service work中不能弹出通知,只有页面可以,页面授权后server worker也可以发送通知.Notification.permission状态变为granted

调用方式有所不同 如下

self.registration.showNotification('hello')

workbox

create-react-app 自带workbox workbox是支持pwa离线缓存的插件