Vue Cli 3 和 Firebase Service Worker 注册

kev*_*guy 9 vue.js service-worker vuejs2 workbox vue-cli

我已经使用 Vue-cli 3 创建了一个 Vue 应用程序,并且我一直在尝试将 FCM 合并到其中。但是,我已经研究了两天,但仍然无法使其正常工作。

首先,这是我的

importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase- app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
var config = {
  messagingSenderId: "69625964474"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function (payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload)
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
      body: 'Background Message body.',
      icon: '/firebase-logo.png'
  }

  return self.registration.showNotification(notificationTitle, notificationOptions)
});
Run Code Online (Sandbox Code Playgroud)

``

sorta 工作的一种解决方案是我将此文件移动到文件public夹中并App.vue使用

const registration = await navigator.serviceWorker.register(`${process.env.BASE_URL}firebase-messaging-sw.js`)
messaging.useServiceWorker(registration)
Run Code Online (Sandbox Code Playgroud)

但是,那么我将有两个 service worker(另一个来自 Vue 本身)。

我尝试vue.config.js通过添加以下配置来修改而不是尝试使用 Workbox:

module.exports = {
  pwa: {
    name: 'My App',
    themeColor: '#4DBA87',
    msTileColor: '#000000',
    appleMobileWebAppCapable: 'yes',
    appleMobileWebAppStatusBarStyle: 'black',

    // configure the workbox plugin
    workboxPluginMode: 'InjectManifest',
    workboxOptions: {
      // swSrc is required in InjectManifest mode.
      swSrc: 'public/firebase-messaging-sw.js'
      // ...other Workbox options...
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在App.vue

const registration = await navigator.serviceWorker.register(`${process.env.BASE_URL}service-worker.js`)
messaging.useServiceWorker(registration)
Run Code Online (Sandbox Code Playgroud)

然后我得到了以下错误:

在此处输入图片说明

如果您对我提到的文件或我的项目目录的外观感到困惑,我所做的只是使用 vue-cli 3 创建了一个 PWA。我保留了大部分结构不变。

我在main.js以下位置设置了 firebase :

import firebase from '@firebase/app'

Vue.config.productionTip = false

const config = {
  apiKey: process.env.VUE_APP_FIREBASE_API_KEY,
  authDomain: process.env.VUE_APP_AUTH_DOMAIN,
  databaseURL: process.env.VUE_APP_DATABASE_URL,
  projectId: process.env.VUE_APP_PROJECT_ID,
  storageBucket: process.env.VUE_APP_STORAGE_BUCKET,
  messagingSenderId: process.env.VUE_APP_MESSAGING_SENDER_ID
}

firebase.initializeApp(config)
Run Code Online (Sandbox Code Playgroud)

然后在App.vue

import firebase from '@firebase/app'
import '@firebase/messaging'

const messaging = firebase.messaging()
messaging.usePublicVapidKey('PUBLIC_KEY')
Run Code Online (Sandbox Code Playgroud)

小智 0

默认情况下,Service Worker 在开发模式下处于禁用状态,因此在开发模式下运行它会导致返回 HTML 错误页面,这就是您收到 text/html 错误的原因,您可以在此处找到详细说明LINK