0

I am trying to send Firebase push notification from my html page to Android app. I am refering this SO answer to implement it. Here is my code:

function post() {
        $.ajax({
            type : 'POST',
            url : "https://fcm.googleapis.com/fcm/send",
            headers : {
                Authorization : 'key=' + 'xxxxxxxxxxxx-xxx-xxxxxxxxxxxxxx'
            },
            contentType : 'application/json',
            data : {
              "to": "/topics/videos",
              "data": {
                "message": "This is push for video!"
               }
            },
            success : function(response) {
                console.log(response);
            },
            error : function(xhr, status, error) {
                console.log(xhr.error);                   
            }
        }); 

Currently, I am facing issue that in response of POST request I am getting following error:

JSON_PARSING_ERROR: Unexpected character (t) at position 0.

Community
  • 1
  • 1
Faisal Shaikh
  • 3,900
  • 5
  • 40
  • 77
  • 2
    Sending messages to devices requires the use of the so-called **server key**. As its name implies, this key should only be present in server-side code. Putting it in client-side code (such as the HTML page you are trying) means that users of your app can take the key and use it to send messages on your behalf to all your users. That's a big security leak. – Frank van Puffelen Nov 12 '16 at 16:30
  • @FrankvanPuffelen Thank you for analyzing the code and let me know. I have already thought about that. This HTML page will be private, it means only admin can see it, but still I would like to know is there anything that can allow me to hide this keys even from admin. – Faisal Shaikh Nov 12 '16 at 16:37
  • Since the key is needed to send a message, the code that send the message will need to access that key. If you run this code on a client's device, they can access that key too and abuse it. If you don't want that, you'll have to run the code in a trusted process (e.g. a small server). – Frank van Puffelen Nov 12 '16 at 16:40
  • You are right but my all clients will not be having server to host website and on other side firebase allow us to host static website. I am still looking for alternative way (without including website) as you said this is not secure. – Faisal Shaikh Nov 12 '16 at 17:22
  • The only secure way it to send from a server. If you search a bit for [questions about Firebase Cloud Messages](http://stackoverflow.com/questions/tagged/firebase-cloud-messaging) to send device-to-device messages, you'll find that this has been covered a lot already. – Frank van Puffelen Nov 12 '16 at 17:38

1 Answers1

1

Try to call

JSON.stringify({"to": "videos", "data": {"message": "This is push for video!"}})

or add option dataType: 'json'

jcubic
  • 61,973
  • 54
  • 229
  • 402