لاستهداف رسالة على أجهزة متعددة، استخدِم
رسائل المواضيع. تتيح لك هذه الميزة إرسال رسالة إلى أجهزة متعدّدة تم تفعيلها لموضوع معيّن.
تركّز هذه المقالة التعليمية على إرسال رسائل المواضيع من خادم تطبيقك باستخدام Admin SDK أو
واجهة برمجة التطبيقات REST
لنظام التشغيل FCM، وتلقّيها ومعالجتها في
تطبيق ويب. سنتناول معالجة الرسائل لكل من
التطبيقات التي تعمل في المقدّمة والخلفية.
أضِف حزمة تطوير البرامج (SDK) لـ Firebase Cloud Messaging JS وفعِّل Firebase Cloud Messaging:
Web
import{initializeApp}from"firebase/app";import{getMessaging}from"firebase/messaging";// TODO: Replace the following with your app's Firebase project configuration// See: https://firebase.google.com/docs/web/learn-more#config-objectconstfirebaseConfig={// ...};// Initialize Firebaseconstapp=initializeApp(firebaseConfig);// Initialize Firebase Cloud Messaging and get a reference to the serviceconstmessaging=getMessaging(app);
Web
importfirebasefrom"firebase/compat/app";import"firebase/compat/messaging";// TODO: Replace the following with your app's Firebase project configuration// See: https://firebase.google.com/docs/web/learn-more#config-objectconstfirebaseConfig={// ...};// Initialize Firebasefirebase.initializeApp(firebaseConfig);// Initialize Firebase Cloud Messaging and get a reference to the serviceconstmessaging=firebase.messaging();
الوصول إلى الرمز المميّز للتسجيل
عندما تحتاج إلى استرداد الرمز المميّز الحالي للتسجيل مثيل تطبيق، عليك أولاً
طلب أذونات الإشعارات من المستخدم باستخدام Notification.requestPermission().
عند الاستدعاء على النحو الموضّح، يعرض هذا الرمز المميّز في حال منح الإذن أو رفض الوعد
في حال الرفض:
تتطلّب FCM ملف firebase-messaging-sw.js.
إذا لم يكن لديك ملف firebase-messaging-sw.js، أنشئ ملفًا فارغًا
بهذا الاسم وضعه في جذر نطاقك قبل استرداد رمز مميّز.
يمكنك إضافة محتوى ذي مغزى إلى الملف لاحقًا في عملية إعداد العميل.
لاسترداد الرمز المميّز الحالي:
Web
import{getMessaging,getToken}from"firebase/messaging";// Get registration token. Initially this makes a network call, once retrieved// subsequent calls to getToken will return from cache.constmessaging=getMessaging();getToken(messaging,{vapidKey:'<YOUR_PUBLIC_VAPID_KEY_HERE>'}).then((currentToken)=>{if(currentToken){// Send the token to your server and update the UI if necessary// ...}else{// Show permission request UIconsole.log('No registration token available. Request permission to generate one.');// ...}}).catch((err)=>{console.log('An error occurred while retrieving token. ',err);// ...});
// Get registration token. Initially this makes a network call, once retrieved// subsequent calls to getToken will return from cache.messaging.getToken({vapidKey:'<YOUR_PUBLIC_VAPID_KEY_HERE>'}).then((currentToken)=>{if(currentToken){// Send the token to your server and update the UI if necessary// ...}else{// Show permission request UIconsole.log('No registration token available. Request permission to generate one.');// ...}}).catch((err)=>{console.log('An error occurred while retrieving token. ',err);// ...});
بعد الحصول على الرمز المميّز، أرسِله إلى خادم تطبيقك وخزِّنه
باستخدام الطريقة المفضّلة لديك.
اشتراك تطبيق العميل في موضوع
يمكنك تمرير قائمة بعلامات تسجيل إلى Firebase Admin SDK
طريقة الاشتراك لاشتراك الأجهزة المقابلة في موضوع:
Node.js
// These registration tokens come from the client FCM SDKs.constregistrationTokens=['YOUR_REGISTRATION_TOKEN_1',// ...'YOUR_REGISTRATION_TOKEN_n'];// Subscribe the devices corresponding to the registration tokens to the// topic.getMessaging().subscribeToTopic(registrationTokens,topic).then((response)=>{// See the MessagingTopicManagementResponse reference documentation// for the contents of response.console.log('Successfully subscribed to topic:',response);}).catch((error)=>{console.log('Error subscribing to topic:',error);});
جافا
// These registration tokens come from the client FCM SDKs.List<String>registrationTokens=Arrays.asList("YOUR_REGISTRATION_TOKEN_1",// ..."YOUR_REGISTRATION_TOKEN_n");// Subscribe the devices corresponding to the registration tokens to the// topic.TopicManagementResponseresponse=FirebaseMessaging.getInstance().subscribeToTopic(registrationTokens,topic);// See the TopicManagementResponse reference documentation// for the contents of response.System.out.println(response.getSuccessCount()+" tokens were subscribed successfully");
Python
# These registration tokens come from the client FCM SDKs.registration_tokens=['YOUR_REGISTRATION_TOKEN_1',# ...'YOUR_REGISTRATION_TOKEN_n',]# Subscribe the devices corresponding to the registration tokens to the# topic.response=messaging.subscribe_to_topic(registration_tokens,topic)# See the TopicManagementResponse reference documentation# for the contents of response.print(response.success_count,'tokens were subscribed successfully')
انتقال
// These registration tokens come from the client FCM SDKs.registrationTokens:=[]string{"YOUR_REGISTRATION_TOKEN_1",// ..."YOUR_REGISTRATION_TOKEN_n",}// Subscribe the devices corresponding to the registration tokens to the// topic.response,err:=client.SubscribeToTopic(ctx,registrationTokens,topic)iferr!=nil{log.Fatalln(err)}// See the TopicManagementResponse reference documentation// for the contents of response.fmt.Println(response.SuccessCount,"tokens were subscribed successfully")
#C
// These registration tokens come from the client FCM SDKs.varregistrationTokens=newList<string>(){"YOUR_REGISTRATION_TOKEN_1",// ..."YOUR_REGISTRATION_TOKEN_n",};// Subscribe the devices corresponding to the registration tokens to the// topicvarresponse=awaitFirebaseMessaging.DefaultInstance.SubscribeToTopicAsync(registrationTokens,topic);// See the TopicManagementResponse reference documentation// for the contents of response.Console.WriteLine($"{response.SuccessCount} tokens were subscribed successfully");
تتيح لك واجهة برمجة التطبيقات Admin FCM API أيضًا إلغاء اشتراك الأجهزة من موضوع معيّن
من خلال تمرير الرموز المميزة للتسجيل إلى الأسلوب المناسب:
Node.js
// These registration tokens come from the client FCM SDKs.constregistrationTokens=['YOUR_REGISTRATION_TOKEN_1',// ...'YOUR_REGISTRATION_TOKEN_n'];// Unsubscribe the devices corresponding to the registration tokens from// the topic.getMessaging().unsubscribeFromTopic(registrationTokens,topic).then((response)=>{// See the MessagingTopicManagementResponse reference documentation// for the contents of response.console.log('Successfully unsubscribed from topic:',response);}).catch((error)=>{console.log('Error unsubscribing from topic:',error);});
جافا
// These registration tokens come from the client FCM SDKs.List<String>registrationTokens=Arrays.asList("YOUR_REGISTRATION_TOKEN_1",// ..."YOUR_REGISTRATION_TOKEN_n");// Unsubscribe the devices corresponding to the registration tokens from// the topic.TopicManagementResponseresponse=FirebaseMessaging.getInstance().unsubscribeFromTopic(registrationTokens,topic);// See the TopicManagementResponse reference documentation// for the contents of response.System.out.println(response.getSuccessCount()+" tokens were unsubscribed successfully");
Python
# These registration tokens come from the client FCM SDKs.registration_tokens=['YOUR_REGISTRATION_TOKEN_1',# ...'YOUR_REGISTRATION_TOKEN_n',]# Unubscribe the devices corresponding to the registration tokens from the# topic.response=messaging.unsubscribe_from_topic(registration_tokens,topic)# See the TopicManagementResponse reference documentation# for the contents of response.print(response.success_count,'tokens were unsubscribed successfully')
انتقال
// These registration tokens come from the client FCM SDKs.registrationTokens:=[]string{"YOUR_REGISTRATION_TOKEN_1",// ..."YOUR_REGISTRATION_TOKEN_n",}// Unsubscribe the devices corresponding to the registration tokens from// the topic.response,err:=client.UnsubscribeFromTopic(ctx,registrationTokens,topic)iferr!=nil{log.Fatalln(err)}// See the TopicManagementResponse reference documentation// for the contents of response.fmt.Println(response.SuccessCount,"tokens were unsubscribed successfully")
#C
// These registration tokens come from the client FCM SDKs.varregistrationTokens=newList<string>(){"YOUR_REGISTRATION_TOKEN_1",// ..."YOUR_REGISTRATION_TOKEN_n",};// Unsubscribe the devices corresponding to the registration tokens from the// topicvarresponse=awaitFirebaseMessaging.DefaultInstance.UnsubscribeFromTopicAsync(registrationTokens,topic);// See the TopicManagementResponse reference documentation// for the contents of response.Console.WriteLine($"{response.SuccessCount} tokens were unsubscribed successfully");