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

使用Cordova Firebase Cloud Messaging插件推送时Device token为空如何解决

可能的原因及解决方案

1. 代码执行逻辑顺序错误

你当前代码中requestPermission和getToken是并行执行的,FCM要求必须先获得通知权限才能正常获取device token,权限未完成授权时调用getToken就会返回空值。需要将getToken逻辑放到权限申请成功的回调中。

2. google-services.json配置错误

  • Cordova Android 9.1.0版本要求google-services.json必须放置在platforms/android/app/目录下,仅放在项目根目录无法被正确识别
  • 检查应用包名、签名文件的SHA1/SHA256指纹是否和Firebase控制台注册的信息完全一致,debug和release版本的签名指纹都需要录入Firebase控制台

3. 插件版本不兼容

新版Cordova FCM插件要求Cordova Android版本≥10.0.0,你使用的9.1.0版本需要安装适配旧版环境的插件,推荐使用cordova-plugin-firebase-messaging@7.x版本,可卸载现有插件后安装指定版本重试。

4. 设备运行环境不满足要求

  • 测试设备必须预装Google Play服务,无GMS的国产定制系统(如华为鸿蒙、国内销售的小米/OPPO/VIVO机型)默认无法运行FCM,会出现token生成失败
  • 设备网络必须可以正常访问Google服务,国内网络需要特殊网络环境才能完成token注册

5. 未监听token刷新回调

你注释掉了onTokenRefresh监听逻辑,部分场景下首次初始化时token不会立刻返回,会通过刷新回调返回,建议取消该部分代码注释,监听回调获取token。


修正后的参考代码

document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
    cordova.plugins.firebase.messaging.onMessage(function (payload) {
        console.log("New foreground FCM message: ", payload);
    });

    cordova.plugins.firebase.messaging.onBackgroundMessage(function (payload) {
        console.log("New background FCM message: ", payload);
    });

    cordova.plugins.firebase.messaging.createChannel({
        id: "mypushid",
        name: "Push channel",
        importance: 3
    });

    // 权限申请成功后再获取token
    cordova.plugins.firebase.messaging.requestPermission({ forceShow: true }).then(function () {
        console.log("You'll get foreground notifications when a push message arrives");
        // 放在权限回调内调用
        cordova.plugins.firebase.messaging.getToken().then(function (token) {
            alert("Got device token: ", token);
        });
    });

    // 取消注释,监听token刷新
    cordova.plugins.firebase.messaging.onTokenRefresh(function () {
        console.log("Device token updated");
        // 刷新后重新获取token
        cordova.plugins.firebase.messaging.getToken().then(function (token) {
            alert("Got new device token: ", token);
        });
    });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 09:00:02