无框架场景下如何使用@capacitor-firebase/messaging插件?
无框架环境集成@capacitor-firebase/messaging 步骤
1. 安装插件
在项目根目录执行以下命令完成插件安装与同步:
npm install @capacitor-firebase/messaging npx cap sync
2. Android端配置(Android Studio内操作)
- 将Firebase控制台下载的
google-services.json文件放置到项目的android/app目录下。 - 确认项目级
build.gradle已添加Firebase服务依赖:dependencies { // 保留原有依赖,新增以下内容 classpath 'com.google.gms:google-services:4.4.1' } - 确认应用级
build.gradle末尾已添加插件引用:apply plugin: 'com.google.gms.google-services'
3. 纯JavaScript(jQuery Mobile)中调用插件
权限请求与令牌获取
在jQuery Mobile页面的pagecreate事件中,结合Capacitor的deviceready事件初始化插件:
$(document).on("pagecreate", "#main-page", function() { document.addEventListener('deviceready', async function() { const { FirebaseMessaging } = Capacitor.Plugins; try { // 请求通知权限 const permResult = await FirebaseMessaging.requestPermissions(); if (permResult.receive === 'granted') { // 获取FCM推送令牌 const fcmToken = await FirebaseMessaging.getToken(); console.log('FCM令牌已获取:', fcmToken); // 此处可将令牌上传至你的后端服务存储 } } catch (err) { console.error('权限请求或令牌获取失败:', err); } }, false); });
监听通知事件
在deviceready事件内添加通知监听逻辑,处理前台接收与点击操作:
document.addEventListener('deviceready', async function() { const { FirebaseMessaging } = Capacitor.Plugins; // 监听前台通知接收 FirebaseMessaging.addListener('notificationReceived', (notification) => { console.log('前台收到通知:', notification); // 用jQuery Mobile弹窗展示通知内容 $('#notification-modal [data-role="header"] h1').text(notification.title); $('#notification-modal [data-role="content"]').text(notification.body); $('#notification-modal').popup('open'); }); // 监听通知点击事件 FirebaseMessaging.addListener('notificationActionPerformed', (action) => { console.log('通知被点击:', action); // 根据通知携带的自定义数据跳转页面 if (action.notification.data.page) { $.mobile.changePage(`#${action.notification.data.page}`); } }); // 处理应用从通知启动的场景 const initialNotify = await FirebaseMessaging.getInitialNotification(); if (initialNotify) { console.log('应用由通知唤醒:', initialNotify); if (initialNotify.data.page) { $.mobile.changePage(`#${initialNotify.data.page}`); } } }, false);
4. 功能验证
- 在Firebase控制台使用获取到的FCM令牌发送测试通知。
- 分别测试前台接收、后台接收、点击通知跳转等场景,确认功能正常。
内容的提问来源于stack exchange,提问作者user2763405
相关产品推荐
相关产品推荐

