【发布时间】:2021-11-09 06:19:02
【问题描述】:
我正在尝试使用他们的 v9 SDK 为 web 实现 Firebase Cloud Messaging,该 SDK 使用 Javascript 模块大力推动......我需要在 Vue 组件中注册服务工作者。
服务人员一直在尖叫“你不能在模块之外使用 import 语句”。所以,我尝试将{type: 'module'} 选项添加到navigator.serviceWorker.register 调用中......但没有运气。我还尝试了老式的importScripts 无济于事。少数在线示例显示 <script type='module'> 但这在 Vue 组件内部毫无意义,至少从我的理解来看是这样。
这是服务工作者的全部内容:
import { fbConfig } from "/js/firebase/firebase-config.js";
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js"
import { getMessaging, onBackgroundMessage } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-messaging-sw.js"
// Create the instance of Firebase & Messaging
const fbApp = initializeApp(fbConfig)
const messaging = getMessaging(fbApp);
onBackgroundMessage(messaging, (payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
const notificationTitle = payload.message.notification.title;
const notificationOptions = payload.message.notification.body;
let outcome = self.registration.showNotification(
notificationTitle,
notificationOptions
);
console.log('[firebase-messaging-sw.js] showNotification outcome', outcome)
});
这是我尝试注册它的地方,它位于我的 Vue 组件的“mounted()”部分中:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register(
'/firebase-messaging-sw.js', {
type: 'module'
})
.then(reg => {
console.log(`Service Worker Registration (Scope: ${reg.scope})`);
})
.catch(error => {
const msg = `Service Worker Error (${error})`;
console.error(msg);
});
} else {
// happens when the app isn't served over HTTPS or if the browser doesn't support service workers
console.warn('Service Worker not available');
}
任何帮助将不胜感激。
【问题讨论】:
标签: javascript firebase vue.js firebase-cloud-messaging service-worker