首页 > 解决方案 > 无法在 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);
});
 

标签: javascriptnode.jsdjangofirebasepush-notification

解决方案


推荐阅读