Skip to content

Instantly share code, notes, and snippets.

@peatiscoding
Created April 18, 2016 17:32
Show Gist options
  • Select an option

  • Save peatiscoding/69e8ffdad35af7d5e809e43fed9f4894 to your computer and use it in GitHub Desktop.

Select an option

Save peatiscoding/69e8ffdad35af7d5e809e43fed9f4894 to your computer and use it in GitHub Desktop.
function GCMCourier(apiKey) {
this.apiKey = apiKey;
this.push = function(notification, callback) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState==4) {
if (xhttp.status == 200) {
var output = xhttp.responseText;
callback && callback(true, output);
} else {
callback && callback(false, xhttp.responseText, xhttp.status);
}
}
}
xhttp.open('POST', 'https://gcm-http.googleapis.com/gcm/send', true);
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.setRequestHeader('Authorization', 'key='+apiKey);
xhttp.send(JSON.stringify(notification));
};
};
@peatiscoding

Copy link
Copy Markdown
Author

Usage:

var courier = new GCMCourier(<GCM secret's key>);
var payload = {
    to: '<device_token>',
    content_available: true,   // for iOS
    notification: {
        title: 'hello',
        body: 'this is from javascript!'
    }
};
courier.push(payload, console.log.bind(console));

For more info please refer to: http://peatiscoding.me/geek-stuff/javascript-to-deliver-gcm-payload/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment