4

I want to send gcm message through javascript code. For this, we need to post a json object.

url and json object format is given in gcm docs: http://developer.android.com/google/gcm/adv.html.

For testing purpose I had written a java code which works perfectly. But the javascript code doesn't work. If anyone has some sample working code(javascript for gcm), please post.

String body = "registration_id=proper_id&data.number=12345678";
byte[] bytes = body.getBytes();
HttpURLConnection conn = getConnection(url);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Authorization", "key=" + key);
OutputStream out = conn.getOutputStream();
out.write(bytes);

javascript code :

var http = new XMLHttpRequest();
var url = "https://android.googleapis.com/gcm/send";
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {        document.getElementById("target").innerHTML =    http.responseText;
}
}
http.open("POST", url, false);
http.setRequestHeader("Content-type", "application/json");
http.setRequestHeader("Authorization", "key=proper_api_key");
var data = '{ "collapse_key": "qcall","time_to_live": 108, "delay_while_idle": true,"data": {"number":"12345678"},"registration_ids":["proper_id"]}';
http.send(data);
Sanmoy
  • 589
  • 2
  • 9
  • 23

1 Answers1

3

This won't work due to Same-origin Policy

In computing, the same-origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site – a combination of scheme, hostname, and port number – to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.

In short: You can't send HTTP Post to other Domains than the one from where your script executes.

Here you can see the rules of the Same-origin Policy

You would need to user your Java Code or if your Hoster does not support Java you could use PHP. This question about GCM and PHP seem to have a working PHP Script for GCM.

Good Luck

Community
  • 1
  • 1
Dodge
  • 8,047
  • 2
  • 30
  • 45