Gcm message through javascript

I want to send a gcm message through javascript code. To do this, we need to place the json object.

The URL and format of the json object are specified in gcm docs: http://developer.android.com/google/gcm/adv.html .

For testing purposes, I wrote Java code that works great. But javascript code is not working. If anyone has a working code example (javascript for gcm) send a message.

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); 
+4
source share
1 answer

This will not work due to policies of the same origin.

In computing, a policy of the same origin is an important security concept for a number of browser-based programming languages, such as JavaScript. This policy allows scripts to run on pages originating from the same site — a combination of a schema, host name, and number port — to access other methods and properties without specific restrictions, but it prevents access to most methods and properties on different pages on different sites.

In short: you cannot send an HTTP message to domains other than those where your script is running.

Here you can find policy rules of the same origin.

You will need custom Java code, or if your hoster does not support Java, you can use PHP. This question about GCM and PHP has a working PHP script for GCM.

Luck

+3
source

All Articles