服务工作者不需要在Webpush的页面重新加载上注销

问题描述

我正在网站中实施推送通知,并且能够成功订阅并接收推送通知

问题是当我重新加载页面时,服务工作人员注销并每次都重新注册。每次注销时,PushManager也会关闭订阅,因此它不再侦听通知。我希望它避免取消注册(如果已注册)。

我不知道为什么会出现这种行为,并长时间坚持了下去。

我正在将Vue.js与pwa一起使用,并添加了具有缓存清除功能的服务工作者。

这是chrome:// gcm-internals的输出

chrome://gcm-internals output

检查元素

输出。重新加载时:

enter image description here

service-worker.js:

workBox.core.setCacheNameDetails({ prefix: 'd4' })
//Change this value every time before you build
const LATEST_VERSION = 'v1.1.1.10'
self.addEventListener('activate',event => {
  console.log(`%c ${LATEST_VERSION} `,'background: #ddd; color: #0000ff')

  if (caches) {
    caches.keys().then(arr => {
      arr.forEach(key => {
        if (key.indexOf('d4-precache') < -1) {
          caches
            .delete(key)
            .then(() =>
              console.log(
                `%c Cleared ${key}`,'background: #333; color: #ff0000'
              )
            )
        } else {
          caches.open(key).then(cache => {
            cache.match('version').then(res => {
              if (!res) {
                cache.put(
                  'version',new Response(LATEST_VERSION,{
                    status: 200,statusText: LATEST_VERSION
                  })
                )
              } else if (res.statusText !== LATEST_VERSION) {
                caches
                  .delete(key)
                  .then(() =>
                    console.log(
                      `%c Cleared Cache ${LATEST_VERSION}`,'background: #333; color: #ff0000'
                    )
                  )
              } else
                console.log(
                  `%c Great you have the latest version ${LATEST_VERSION}`,'background: #333; color: #00ff00'
                )
            })
          })
        }
      })
    })
  }

  self.addEventListener('push',event => {
    const { title,options } = event.data.json()
    console.log('Push Received...',title,options)
    /*const notif =
      .catch(err => {
        console.error('error showing notification',err)
      })*/
    event.waitUntil(self.registration.showNotification(title,options))
  })

  self.addEventListener('notificationclick',function(event) {
    event.notification.close()
    event.waitUntil(clients.openWindow(event.notification.data.url))
  })
})

workBox.skipwaiting()
workBox.clientsClaim()

self.__precacheManifest = [].concat(self.__precacheManifest || [])
workBox.precaching.suppressWarnings()
workBox.precaching.precacheAndRoute(self.__precacheManifest,{})

registerServiceWorker.js:

/* eslint-disable no-console */

import { register } from 'register-service-worker'

if (process.env.NODE_ENV === 'production') {
  register(`${process.env.BASE_URL}service-worker.js`,{
    ready() {
      console.log(
        'App is being served from cache by a service worker.\n' +
          'For more details,visit ...'
      )
    },registered() {
      console.log('Service worker has been registered.')
    },cached() {
      console.log('Content has been cached for offline use.')
    },updatefound() {
      console.log('New content is downloading.')
    },updated() {
      console.log('New content is available; please refresh.')
      setTimeout(() => {
        window.location.reload(true)
      },1000)
      //window.location = window.location.href + '?eraseCache=true'
    },offline() {
      console.log(
        'No internet connection found. App is running in offline mode.'
      )
    },error(error) {
      console.error('Error during service worker registration:',error)
    }
  })
}

webpack.config.js module.exports.plugins,仅与服务人员相关的部分:

const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin')

module.exports.plugins = [
new SWPrecacheWebpackPlugin({
      cacheId: 'my-pwa-vue-app',filename: 'service-worker-cache.js',staticFileGlobs: ['dist/**/*.{js,css}','/'],minify: true,stripPrefix: 'dist/',dontCacheBustUrlsMatching: /\.\w{6}\./
    })
]

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)