Patricio Vargas
Patricio Vargas

Reputation: 5522

Trying to subscribe to topic on Firebase Cloud Messaging gives Error

When i try to subscribe to a topic i get the following error:

.subscribeToTopic is not a function

const messaging = firebase.messaging();
      messaging
        .requestPermission()
        .then(() => {
          return messaging.getToken();
        })
        .then(token => {
          messaging
            .subscribeToTopic(token, 'allUsers')
            .then(response=> {
              console.log(JSON.stringify(response));
            })
            .catch(function(error) {
              console.log('Error subscribing to topic:', error);
            });
        })
        .catch(err => {
          console.log('Unable to get permission to notify.', err);
        });

If I remove that line of .subscribeToTopic and add a POST call via http it works using the following url: https://iid.googleapis.com/iid/v1/TOKEN/rel/topics/TOPIC_NAME

I took a look to this question and the docs Cloud Messaging in Cloud Functions: admin.messagin(...).send is not a function

https://firebase.google.com/docs/cloud-messaging/js/topic-messaging

Upvotes: 2

Views: 9168

Answers (2)

Yogi Arif Widodo
Yogi Arif Widodo

Reputation: 679

ah i solved it by handling on backend side ( nodeJS ) where the documentation is easy to handle topic.

so in this case we have alr generate token on frontend side then in backend (nodeJS) we tried to subscribe to topic by the token.

so in frontend end when we stream or firebase.messaging().onMessage(payload => { would like to trigger and show the message by topic.

FYI : https://github.com/firebase/firebase-js-sdk/issues/5289#issuecomment-899542765

so from the link we know that Notification.vue

// these from frontend side ( for example vueJS )
import firebase from 'firebase/app'
import 'firebase/messaging'
// firebase only for get token, onMessaging, request permission check, there is no function to subscribe topic by the token, so we handle on backend side my alternative

then in server.js

// these from backend side ( for examle nodeJS )
const { admin } = require('./firebase-config');
// admin.messaging().sendToTopic()
// admin.messaging().subscribeToTopic()
// admin.messaging().sendToDevice()

if you are looking for the firebase-config.js here is

/*
 * Initialize firebase
 */
var admin = require("firebase-admin");

var serviceAccount = require("./firebase.json"); // you can get the .json file on firebase service account .

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://project-xxxxxxx.firebaseio.com"
});
module.exports.admin = admin

my implementation :

app.get('/firebase/notification', (req, res)=>{
  const registrationToken = req.body.registrationToken;

  admin.messaging().subscribeToTopic(registrationToken, 'myTopic')
      .then(response => {
        console.log('Successfully subscribed to topic:', response)

        const options =  notification_options;
        const message_notification = {
          notification: {
            title: 'Yogi Arif Widodo',
            body: '2 10 pm',
            url: 'https://localhost:8080',
            other: 'other data',
          }
        };
        admin.messaging().sendToTopic('myTopic', message_notification, options).then( response => {

so when i tested on firebase console send by topic myTopic my Notification.vue trigger these code

firebase.messaging().onMessage(payload => {
.....console.log
}

Upvotes: 2

Peter Haddad
Peter Haddad

Reputation: 80914

You need to use the method send not sendToTopic:

// The topic name can be optionally prefixed with "/topics/".
var topic = 'highScores';

var message = {
  data: {
    score: '850',
    time: '2:45'
  },
  topic: topic
};

// Send a message to devices subscribed to the provided topic.
admin.messaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

send() was released and replaced sendtotopic/sendtodevice in version FCM v1

https://firebase.googleblog.com/2018/02/firebase-cloud-messaging-v1-now.html

https://firebase.google.com/docs/cloud-messaging/js/topic-messaging

Upvotes: 0

Related Questions