How to subscribe to topics with web browser using Firebase Cloud Messaging

前端 未结 4 777
梦毁少年i
梦毁少年i 2020-11-29 05:01

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

4条回答
  •  无人及你
    2020-11-29 05:27

    Franks solution is still valid. However you need to have a server that does the subscribe for you.

    function subscribeTokenToTopic(token, topic) {
      fetch('https://myserver.com/'+token+'/rel/topics/'+topic, {
        method: 'POST',
        headers: new Headers({
          'Authorization': 'Bearer '+ oauthToken
        })
      }).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);
      })
    }
    

    then your server has a rest call something like this:

    (java spring)

    @RequestMapping(value = "/{token}/rel/topics/{topic}", method = RequestMethod.POST)
    public ResponseEntity subscribeTokenToTopic(@PathVariable("token") String token, @PathVariable("topic") String topic)  throws ServletException {
      URL url = new URL("https://iid.googleapis.com/iid/v1/"+token+"/rel/topics/"+topic);
      // make https post call here.. 
      ...
    }
    

    Hopefully that makes sense.

提交回复
热议问题