You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter集成Firebase推送通知报错:ServiceWorker MIME类型不支持

问题分析

错误提示表明Firebase Messaging无法注册默认Service Worker,核心原因是请求firebase-messaging-sw.js时返回了text/html类型内容——这意味着该文件不存在,或者服务器没有正确返回它的JavaScript MIME类型。

解决方案

1. 创建并配置Firebase Messaging Service Worker文件

在项目的web根目录(与index.html同级)创建firebase-messaging-sw.js文件,填入以下内容(替换为你的Firebase项目配置):

importScripts('https://www.gstatic.com/firebasejs/9.23.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.23.0/firebase-messaging-compat.js');

// 替换为你的Firebase项目配置
firebase.initializeApp({
  apiKey: "你的API_KEY",
  authDomain: "你的AUTH_DOMAIN",
  projectId: "你的PROJECT_ID",
  storageBucket: "你的STORAGE_BUCKET",
  messagingSenderId: "你的MESSAGING_SENDER_ID",
  appId: "你的APP_ID"
});

const messaging = firebase.messaging();

// 可选:处理后台推送消息
messaging.onBackgroundMessage(function(payload) {
  const notificationTitle = payload.notification.title;
  const notificationOptions = {
    body: payload.notification.body,
    icon: '/icons/Icon-192.png'
  };

  self.registration.showNotification(notificationTitle, notificationOptions);
});

2. 更新Web端初始化配置

在web/index.html的<head>标签内添加Firebase初始化脚本,确保在Flutter加载前完成Firebase配置:

<!-- 添加到<head>内 -->
<script src="https://www.gstatic.com/firebasejs/9.23.0/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.23.0/firebase-messaging-compat.js"></script>
<script>
  // 替换为你的Firebase项目配置
  const firebaseConfig = {
    apiKey: "你的API_KEY",
    authDomain: "你的AUTH_DOMAIN",
    projectId: "你的PROJECT_ID",
    storageBucket: "你的STORAGE_BUCKET",
    messagingSenderId: "你的MESSAGING_SENDER_ID",
    appId: "你的APP_ID"
  };

  firebase.initializeApp(firebaseConfig);
</script>

3. 修正Dart代码中的Firebase Messaging初始化

在Flutter的初始化代码中,指定Service Worker路径并配置VAPID密钥(VAPID密钥可在Firebase控制台>Cloud Messaging>Web配置中生成):

import 'package:firebase_messaging/firebase_messaging.dart';

Future<void> initFirebaseMessaging() async {
  await FirebaseMessaging.instance.setAutoInitEnabled(true);
  // 替换为你的VAPID密钥
  await FirebaseMessaging.instance.getToken(vapidKey: "你的VAPID_KEY");
  // 显式注册自定义Service Worker
  await FirebaseMessaging.instance.registerServiceWorker(
    serviceWorkerUrl: '/firebase-messaging-sw.js',
  );
}

4. 修正Gradle配置中的拼写错误

你的项目级build.gradle中存在依赖拼写错误:
原代码:

classpath 'com.google.gms.google-service:4.4.0'

修正为(末尾少了s):

classpath 'com.google.gms.google-services:4.4.0'

5. 清理并重新构建项目

执行以下命令确保资源正确打包:

flutter clean
flutter pub get
flutter run -d chrome

内容的提问来源于stack exchange,提问作者Ayush V Jain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 01:37:35