如何使用 Firebase Cloud Messaging 通过网络浏览器订阅主题 [英] How to subscribe to topics with web browser using Firebase Cloud Messaging

查看:20
本文介绍了如何使用 Firebase Cloud Messaging 通过网络浏览器订阅主题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种使用 Firebase Cloud Messaging 向我应用的所有用户发送通知的方法,但我有一个仅限网络的应用.我见过似乎适用于 Android/iOS 的解决方案,这基本上涉及让用户自动订阅名为allDevices"的主题,然后向订阅该主题的所有用户发送通知.我似乎找不到任何关于如何让基于 Web 的用户订阅主题的文档.有谁知道这是否可行,如果可行,是否有我遗漏的文档可以涵盖这一点?

I'm trying to find a way to send a notification using Firebase Cloud Messaging to all of my app's users, but I have a web-only app. I've seen solutions that appear to be for Android/iOS, which basically involves having the users auto-subscribe to a topic called "allDevices" and then sending a notification to all users subscribed to that topic. I just can't seem to find any documentation on how to have a web-based user subscribe to a topic. Does anyone know if that's possible, and if it is, is there documentation that I've missed that would cover that?

谢谢!

推荐答案

Firebase Cloud Messaging SDK for JavaScript 中没有直接的 API 来为客户端订阅主题.相反,您可以通过 REST API 将令牌订阅到主题.调用此 API 需要您指定 FCM 服务器密钥,这意味着您只能在受信任的环境中执行此操作,例如您的开发机器、您控制的服务器或 Cloud Functions.这是必要的,因为拥有 FCM 服务器密钥允许代表您的应用向您应用的所有用户发送消息.

There is no direct API to subscribe clients to topics in the Firebase Cloud Messaging SDK for JavaScript. Instead you can subscribe a token to a topic through the REST API. Calling this API requires that you specify the FCM server key, which means that you should only do this on a trusted environment, such as your development machine, a server you control, or Cloud Functions. This is necessary, since having the FCM server key allows sending messages on your app's behalf to all of your app's users.

事实证明,在我的测试中,我使用了一个较旧的项目,其中客户端 API 密钥允许订阅主题.出于安全原因,此功能已从较新的项目中删除.

It turns out that in my tests I was using an older project, where client API keys were allows to subscribe to topics. This ability has been removed from newer projects for security reasons.

例如,在 Node.js 中,您可以调用 REST API 来创建一个应用程序实例的关系映射像这样:

In Node.js you could for example call the REST API to create a relation mapping for an app instance like this:

function subscribeTokenToTopic(token, topic) {
  fetch('https://iid.googleapis.com/iid/v1/'+token+'/rel/topics/'+topic, {
    method: 'POST',
    headers: new Headers({
      'Authorization': 'key='+fcm_server_key
    })
  }).then(response => {
    if (response.status < 200 || response.status >= 400) {
      throw 'Error subscribing to topic: '+response.status + ' - ' + response.text();
    }
    console.log('Subscribed to "'+topic+'"');
  }).catch(error => {
    console.error(error);
  })
}

其中 fcm_server_key 是 FCM 服务器密钥,取自您项目的 Firebase 控制台.

Where fcm_server_key is the FCM server key, taken from the Firebase console of your project.

这篇关于如何使用 Firebase Cloud Messaging 通过网络浏览器订阅主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆