javascript - 无法在 firebase-messaging-sw.js 中导入 firebase 模块
问题描述
我正在开发firebase消息服务,通过django web应用程序向Andriod、IOS和网站上的web应用程序发送推送通知,我设法获取令牌并运行sw,但是由于导入模块问题,我无法运行sw并获取消息,我尝试了所有导入语句,但没有一个对我有用!!,
当我运行以下行时,我收到此错误“未捕获的 DOMException:无法在 'WorkerGlobalScope' 上执行 'importScripts':
importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-sw.js');
当我运行这些时,我得到了这个错误“不能在模块外使用导入语句”:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js";
import { getMessaging } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-sw.js";
注意我在访问 localhost:/firebase-messaging-sw.js 并打开下载窗口以下载 firebase-messaging-sw.js 文件时没有任何错误
请找到 firebase-messaging-sw.js 文件供您参考:
// import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js";
// import { getMessaging } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-sw.js";
importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging.js');
self.importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-sw.js');
// import { initializeApp } from "./node_modules/@firebase/app";
// import { getMessaging } from "./node_modules/@firebase/messaging/sw";
// import { getMessaging } from "./firebase/@firebase/messaging/sw";
// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
const BikumApp = firebase.initializeApp({
apiKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
authDomain: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
databaseURL: 'xxxxxxxxxxxxxxxxxxxxxxxxxx',
projectId: 'xxxxxxxxxxxxxxxxxxxxxx',
storageBucket: 'xxxxxxxxxxxxxxxxxxxxxxx',
messagingSenderId: 'xxxxxxxxxxxxxxxxx',
appId: "1xxxxxxxxxxxxxxxxxxxxxxxxxx",
measurementId: 'xxxxxxxxxxxxxxxxxx',
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebae.getMessaging(BikumApp)
console.log(messaging);
// const messaging = getMessaging();
onBackgroundMessage(messaging, (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'
};
registration.showNotification(notificationTitle,
notificationOptions);
});
解决方案
推荐阅读
- python - 类中的多处理未使用完整的 CPU 范围
- google-cloud-platform - 检测数据状态变化的最佳架构/数据结构是什么
- asp.net - 在 vb.net 中的输入字段上键入时从数据库中读取搜索查询
- php - 将选择框添加到 Woocommerce 中的链接产品选项卡
- npm - registry.npmjs.org 请求超时
- r - 通过替换双循环更快的矩阵乘法
- react-native - 如果在反应原生 android 的水平平面列表行中添加 WebView 不可滚动
- django - 从多表中选择原始数据
- mysql - 当 Sequelize.findAll 在另一个文件上时,导出函数不返回数据
- java - 在 NetBeans 上使用 JDK 13 运行 Java 应用程序