无法将Vue.js PWA添加到主屏幕

use*_*221 4 web-applications progressive web vue.js

我最近正在深入研究渐进式Web应用程序.我已经将我的manifest.json和sw.js链接起来了:

在index.html中

<link rel="manifest" href="<%= htmlWebpackPlugin.files.publicPath %>static/manifest.json">
Run Code Online (Sandbox Code Playgroud)

在我的main.js

if('serviceWorker' in navigator) {
        const messaging = firebase.messaging()

        navigator.serviceWorker.register('/static/sw.js').then((registration) => {
            messaging.useServiceWorker(registration)
            console.log('Service Worker registered')
        }).catch((error) => {
            console.log('Service Worker failed to register')
        })
    }
Run Code Online (Sandbox Code Playgroud)

看起来它有效,但当我尝试使用DevTools将webapp添加到我的主屏幕时,它显示以下错误:"无法安装站点:未检测到匹配的服务工作者.您可能需要重新加载页面,或检查当前页面的服务工作者还控制清单中的起始URL"

在做了一些研究后,我发现有人说将sw.js和manifest.json放在项目的根目录中.但是当我这样做时,它不会链接文件(当我把它们放在静态文件夹中时,它会链接它们).顺便说一下,我正在使用标准的Vue.js模板.

有任何建议如何解决这个问题?

Ari*_*yen 6

服务工作者未能注册的原因可能是其中之一:

  1. 您没有通过HTTPS运行应用程序.
  2. 服务工作者文件的路径编写不正确 - 需要相对于源而不是应用程序的根目录编写.

结构方面,它应该是这样的

/static/
    /css/
    /js/
    /img/
manifest.json
index.html
service-worker.js
Run Code Online (Sandbox Code Playgroud)

在索引文件中,您应该注册与此类似的服务工作者

<script type=text/javascript>
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/service-worker.js')
    .then(function(registration) {
      console.log('Registration successful, scope is:', registration.scope);
    })
    .catch(function(error) {
      console.log('Service worker registration failed, error:', error);
    });
  }
</script>
Run Code Online (Sandbox Code Playgroud)

并连接manifest.json

<link rel=manifest href=/manifest.json>
Run Code Online (Sandbox Code Playgroud)

manifest.json的内容可以是

{
  "name": "vue-vanilla-pwa",
  "short_name": "vue-vanilla-pwa",
  "icons": [
    {
      "src": "/static/img/icons/android-chrome-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "/static/img/icons/android-chrome-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ],
  "start_url": "/index.html",
  "display": "standalone",
  "background_color": "#000000",
  "theme_color": "#4DBA87"
}
Run Code Online (Sandbox Code Playgroud)

sw-precache专为满足预先缓存某些关键静态资源的需求而设计.因此,如果您想在用户离线时对服务工作者执行其他操作,则不需要它.以下是您可以对服务工作人员执行的操作的示例列表:https://github.com/GoogleChrome/samples/tree/gh-pages/service-worker