mcpField
C
capacitor-push-notifications

capacitor-push-notifications

github.com/cap-go开发751.1k 次安装2 周前更新
代码仓库

关于 capacitor-push-notifications

capacitor-push-notifications 是面向 Capacitor 开发者的推送通知集成与排错技能,主要涵盖官方 @capacitor/push-notifications 插件。它指导 iOS、Android 配置、令牌注册、前台展示和设备验证。

主要功能

  1. 01指导推送插件选择与安装
  2. 02配置 iOS APNs 与 Android Firebase
  3. 03按顺序注册监听器、权限和令牌
  4. 04设置前台通知展示选项
  5. 05验证通知并排查常见错误

适用场景

  1. 01为 Capacitor 应用添加远程推送
  2. 02排查注册令牌未触发或平台不一致
  3. 03处理前台与后台通知展示差异
  4. 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.json
references/
android-setup.md
ios-setup.md
sending.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/。

工作流

  1. 检查: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。
  2. 安装:npm install @capacitor/push-notifications && npx cap sync。
  3. iOS:功能、APNs 密钥和 AppDelegate 转发。详情:references/ios-setup.md。
  4. Android:google-services.json、通知渠道、图标、权限。详情:references/android-setup.md。
  5. JS:先添加监听器,再请求权限,然后调用 register()(如下)。
  6. 后端:发送测试消息。负载格式:references/sending.md。
  7. 在实体设备上根据下方清单验证。

仅在涉及相应主题时加载参考资料。

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 可替代已弃用的 iOS alert。Capacitor 9 在 iOS 上移除了 alert;升级时请替换它。badge 仅适用于 iOS。
  • 空数组表示前台不显示任何内容;请自行处理 pushNotificationReceived。

Capacitor 版本说明

版本变更
7firebaseMessagingVersion 默认值为 24.1.0
8firebaseMessagingVersion 默认值为 25.0.1
8.5UIScene 生命周期。远程通知回调(didRegisterForRemoteNotificationsWithDeviceToken、didFailToRegister...)仍保留在 AppDelegate 中,并继续正常工作。不要将它们移至 SceneDelegate。原本使用 AppDelegate application(_:open:) 的点击路由必须迁移(参见 capacitor-deep-linking)。
9移除 iOS alert 展示选项;iOS 最低版本为 16;@main 取代 @UIApplicationMain;google-services Gradle 插件版本为 4.5.0

验证

  1. iOS:codesign -d --entitlements :- path/to/App.app | grep aps-environment 会显示 development(调试版)或 production(TestFlight/App Store)。
  2. Android:接受提示后,adb shell dumpsys package com.example.app | grep POST_NOTIFICATIONS 会显示 granted=true。
  3. 应用会在真实设备上记录一个 registration 令牌(Apple 芯片上的 iOS Simulator 可通过 xcrun simctl push 接收推送,但请在设备上测试真实的 APNs)。
  4. 从 Firebase Console(Messaging -> "Send test message")或后端向该令牌发送测试消息。
  5. 检查所有三种状态:前台(展示 + pushNotificationReceived)、后台(系统托盘)、已终止(点击后由 pushNotificationActionPerformed 正确路由)。
  6. 无需服务器的 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-errorAPNs 密钥未上传到 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

资源

评论

支持 Markdown