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

messaging.onBackgroundMessage不是函数错误及通知无标题正文问题求助

解决messaging.onBackgroundMessage is not a function错误及通知无标题正文问题

问题原因

  • 你使用的Firebase SDK版本为3.5.0,onBackgroundMessage方法是在Firebase Messaging v7.0.0之后才新增的API,旧版本不支持该方法,因此触发报错。
  • 通知能送达但无标题正文,是因为Service Worker内的自定义通知逻辑因上述错误无法执行,只能触发浏览器默认的空通知。

修复步骤

1. 升级Firebase SDK版本

将Service Worker中的importScripts链接替换为支持onBackgroundMessage的新版本(推荐使用v8.x稳定版,兼容旧写法):

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

2. 删除Service Worker内的自注册代码

firebase-messaging-sw.js作为Service Worker文件,不能自行注册自己,这段注册逻辑应该放在网页的主JS文件中。删除以下代码:

// 需移除的错误代码
if ('serviceWorker' in navigator) {
  navigator.serviceWorker
    .register('../firebase-messaging-sw.js')
    .then(function (registration) {
      console.log('Registration successful, scope is:', registration.scope)
    })
    .catch(function (err) {
      console.log('Service worker registration failed, error:', err)
    })
}

3. 修正后的完整Service Worker代码

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

firebase.initializeApp({
  messagingSenderId: '576646393071',
})

const messaging = firebase.messaging()

messaging.onBackgroundMessage((payload) => {
  console.log('[firebase-messaging-sw.js] Received background message ', payload)
  // 优先使用消息payload中的通知内容,无内容时用默认值
  const notificationTitle = payload.notification?.title || 'Background Message Title'
  const notificationOptions = {
    body: payload.notification?.body || 'Background Message body.',
    icon: '/firebase-logo.png'
  }

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

4. 刷新Service Worker

在浏览器开发者工具的Application -> Service Workers面板中,点击Unregister清除旧的Service Worker,然后刷新页面使新配置生效。

内容的提问来源于stack exchange,提问作者Saikrishna Reddy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 05:10:33