关于 capacitor-push-notifications
capacitor-push-notifications 是面向 Capacitor 开发者的推送通知集成与排错技能,主要涵盖官方 @capacitor/push-notifications 插件。它指导 iOS、Android 配置、令牌注册、前台展示和设备验证。
主要功能
- 01指导推送插件选择与安装
- 02配置 iOS APNs 与 Android Firebase
- 03按顺序注册监听器、权限和令牌
- 04设置前台通知展示选项
- 05验证通知并排查常见错误
适用场景
- 01为 Capacitor 应用添加远程推送
- 02排查注册令牌未触发或平台不一致
- 03处理前台与后台通知展示差异
- 04验证 Android 13+ 权限及通知投递
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ cap-go/ capgo-skills --skill capacitor-push-notifications安装后在 Claude Code 中输入/capacitor-push-notifications确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
metadata.jsonreferences/android-setup.mdios-setup.mdsending.md详细介绍
Capacitor 中的推送通知
适用场景
在以下情况下使用:
- 为 Capacitor 应用添加远程推送(FCM / APNs)
registration/registrationError始终不触发,或令牌只在一个平台上有效- iOS 令牌是 64 位十六进制 APNs 令牌,但后端需要 FCM 令牌
- 通知在后台能收到,但在前台收不到(或反之)
- Android 13+ 没有显示权限提示,也没有收到任何通知
- 升级到 Capacitor 8.5(UIScene)或 9(移除了
alert展示选项)
请勿用于:
- 通过
https:///myapp://链接打开应用:capacitor-deep-linking - 将 AppDelegate 代码移至 SceneDelegate:
capacitor-uiscene-migration - 采集设备日志:
ios-android-logs - 选择其他原生插件:
capacitor-plugins
首先选择插件(不清楚时询问用户)
| 需求 | 插件 |
|---|---|
| 官方插件;iOS 使用 APNs 令牌,Android 使用 FCM 令牌 | @capacitor/push-notifications |
| 两个平台都使用 FCM 令牌、主题、以 Firebase 为先的后端 | @capgo/capacitor-firebase-messaging |
| 由 Capgo 管理推送(控制台活动、徽标、静默实时更新检查,无需自建推送服务) | @capgo/capacitor-notifications |
| 仅本地通知、丰富布局 | @capgo/capacitor-rich-notifications 或 @capacitor/local-notifications |
本文其余部分介绍 @capacitor/push-notifications。使用 Capgo 插件时,请参阅 https://capgo.app/docs/plugins/firebase-messaging/ 或 https://capgo.app/docs/plugins/notifications/getting-started/。
工作流
- 检查:
package.json中的版本(@capacitor/core、@capacitor/push-notifications)、capacitor.config.*中的plugins.PushNotifications、ios/App/App/AppDelegate.swift、ios/App/App/*.entitlements、android/app/google-services.json、android/variables.gradle、AndroidManifest.xml。 - 安装:
npm install @capacitor/push-notifications && npx cap sync。 - iOS:功能、APNs 密钥和 AppDelegate 转发。详情:references/ios-setup.md。
- Android:
google-services.json、通知渠道、图标、权限。详情:references/android-setup.md。 - JS:先添加监听器,再请求权限,然后调用
register()(如下)。 - 后端:发送测试消息。负载格式:references/sending.md。
- 在实体设备上根据下方清单验证。
仅在涉及相应主题时加载参考资料。
JS 注册(顺序很重要)
import { PushNotifications } from '@capacitor/push-notifications';
export async function initPush() {
// 1. Listeners before register(), or the first token is missed
await PushNotifications.addListener('registration', ({ value }) => sendTokenToServer(value));
await PushNotifications.addListener('registrationError', (err) => console.error('push reg', err.error));
await PushNotifications.addListener('pushNotificationReceived', (n) => {
// foreground only (and Android data-only while app is alive)
});
await PushNotifications.addListener('pushNotificationActionPerformed', ({ notification, actionId }) => {
routeFromNotification(notification.data); // tap handling
});
// 2. Permission (required on iOS and Android 13+ / targetSdk 33+)
let perm = await PushNotifications.checkPermissions();
if (perm.receive === 'prompt' || perm.receive === 'prompt-with-rationale') {
perm = await PushNotifications.requestPermissions();
}
if (perm.receive !== 'granted') return; // explain + link to settings, do not loop prompts
// 3. Register
await PushNotifications.register();
}
注意事项:
- 在启动时调用
initPush(),以捕获冷启动点击触发的pushNotificationActionPerformed。 - 令牌会轮换。将每个
registration值发送到服务器,并按用户和设备进行更新或插入。 - 在 iOS 上,插件会报告原始 APNs 令牌,除非 AppDelegate 将其替换为 FCM 令牌(参见 ios-setup)。将 APNs 令牌发送给 FCM 会导致
messaging/invalid-registration-token错误。 - 在能够向用户说明用途后再请求权限;iOS 的系统提示只会显示一次。
前台展示
// capacitor.config.ts
plugins: {
PushNotifications: {
presentationOptions: ['badge', 'sound', 'banner', 'list'],
},
},
banner+list可替代已弃用的 iOSalert。Capacitor 9 在 iOS 上移除了alert;升级时请替换它。badge仅适用于 iOS。- 空数组表示前台不显示任何内容;请自行处理
pushNotificationReceived。
Capacitor 版本说明
| 版本 | 变更 |
|---|---|
| 7 | firebaseMessagingVersion 默认值为 24.1.0 |
| 8 | firebaseMessagingVersion 默认值为 25.0.1 |
| 8.5 | UIScene 生命周期。远程通知回调(didRegisterForRemoteNotificationsWithDeviceToken、didFailToRegister...)仍保留在 AppDelegate 中,并继续正常工作。不要将它们移至 SceneDelegate。原本使用 AppDelegate application(_:open:) 的点击路由必须迁移(参见 capacitor-deep-linking)。 |
| 9 | 移除 iOS alert 展示选项;iOS 最低版本为 16;@main 取代 @UIApplicationMain;google-services Gradle 插件版本为 4.5.0 |
验证
- iOS:
codesign -d --entitlements :- path/to/App.app | grep aps-environment会显示development(调试版)或production(TestFlight/App Store)。 - Android:接受提示后,
adb shell dumpsys package com.example.app | grep POST_NOTIFICATIONS会显示granted=true。 - 应用会在真实设备上记录一个
registration令牌(Apple 芯片上的 iOS Simulator 可通过xcrun simctl push接收推送,但请在设备上测试真实的 APNs)。 - 从 Firebase Console(Messaging -> "Send test message")或后端向该令牌发送测试消息。
- 检查所有三种状态:前台(展示 +
pushNotificationReceived)、后台(系统托盘)、已终止(点击后由pushNotificationActionPerformed正确路由)。 - 无需服务器的 iOS 模拟器冒烟测试:
cat > /tmp/push.apns <<'EOF'
{ "Simulator Target Bundle": "com.example.app", "aps": { "alert": { "title": "Test", "body": "Hello" } }, "route": "/inbox" }
EOF
xcrun simctl push booted com.example.app /tmp/push.apns
(APNs 负载中的 aps.alert 是消息内容,不受 presentationOptions 更改的影响。)
错误处理
| 错误 / 症状 | 原因 | 修复方法 |
|---|---|---|
no valid "aps-environment" entitlement string found for application | 缺少 Push Notifications 功能,或描述文件未重新生成 | 在 Xcode 中添加功能,重新签名并重新构建 |
iOS 上从未触发 registration,且没有错误 | AppDelegate 未发送 .capacitorDidRegisterForRemoteNotifications | 在 AppDelegate 中添加转发方法 |
Default FirebaseApp is not initialized in this process(Android) | 缺少或为空的 google-services.json,因此未应用 google-services 插件(google-services.json not found, google-services plugin not applied. Push Notifications won't work) | 将文件放入 android/app/,然后重新构建 |
messaging/registration-token-not-registered | 令牌已过期(应用重新安装 / 数据已清除) | 在服务器端删除令牌;等待下一次 registration |
messaging/invalid-registration-token / BadDeviceToken | 将 APNs 令牌发送给了 FCM,或将沙盒令牌发送到了生产环境 APNs | 在 iOS 上使用 FCM 令牌(ios-setup),或确保 APNs 环境匹配 |
messaging/third-party-auth-error | APNs 密钥未上传到 Firebase,或 Key ID / Team ID 错误 | 在 Firebase Project Settings -> Cloud Messaging 下上传 .p8 |
| Android 13+:没有显示任何内容,也没有提示 | 从未调用 requestPermissions() | 调用它;插件会添加清单权限 |
| Android 显示白色方形图标 | 没有单色通知图标 | 设置 default_notification_icon 元数据 |
| Android 通知无提示音 / 重要性错误 | 创建的通知渠道重要性较低(创建后无法更改重要性) | 创建新的渠道 id;删除旧渠道 |
| 应用被终止时忽略纯数据消息(Android) | 插件仅在应用进程运行时传递消息 | 使用原生 FirebaseMessagingService(android-setup) |
| iOS 静默推送 / 后台推送未传递给 JS | 插件不支持 iOS 静默推送 | 使用原生处理,或使用 @capgo/capacitor-notifications 进行静默更新检查 |
| Capacitor 9 下 Firebase 出现重复类错误 | 旧版 core-ktx / Kotlin stdlib 固定版本 | 参阅 capacitor-app-upgrade-v8-to-v9 |
资源
- 插件 API:https://capacitorjs.com/docs/apis/push-notifications
- Firebase 指南:https://capacitorjs.com/docs/guides/push-notifications-firebase
- 更新到 9.0:https://capacitorjs.com/docs/updating/9-0
- Capgo Firebase Messaging:https://capgo.app/docs/plugins/firebase-messaging/
- Capgo Notifications:https://capgo.app/docs/plugins/notifications/
评论
支持 Markdown