如何在fcm-django推送通知中添加跳转链接?
实现FCM通知点击跳转Web应用指定页面
要实现点击FCM通知打开Web应用的指定页面,你需要结合通知消息和数据消息:后端推送时携带目标链接,前端监听通知点击事件并处理跳转。
1. 修改后端推送代码
在Message中添加data字段传入目标页面链接,同时修正你代码中类名的大小写问题(导入的Message和Notification首字母需小写):
from firebase_admin.messaging import Message, Notification from fcm_django.models import FCMDevice fcm_devices_of_this_user = FCMDevice.objects.filter(user=user_obj, active=True) if fcm_devices_of_this_user: fcm_devices_of_this_user.send_message( Message( notification=Notification(title=notification_for, body=message), data={ "target_url": "https://your-web-app.com/your-target-page" # 替换为你的目标页面链接 } ) )
2. Web客户端处理通知点击
在Web应用的Service Worker中,监听notificationclick事件,读取data中的链接并打开页面:
self.addEventListener('notificationclick', function(event) { // 关闭通知弹窗 event.notification.close(); // 获取后端传入的目标链接 const targetUrl = event.notification.data.target_url; if (targetUrl) { // 打开目标页面 event.waitUntil( clients.openWindow(targetUrl) ); } });
注意事项
- 确保Web应用已正确配置FCM Service Worker,且用户已授权接收通知。
data字段的键名可自定义,只要前后端保持一致即可。- 若需在Android/iOS端实现跳转,逻辑类似:在对应平台的通知点击回调中读取
data里的链接并处理。
内容的提问来源于stack exchange,提问作者mahmudsajib
相关产品推荐
相关产品推荐

