Google Cloud Messaging (GCM) is a service for both Android-powered device and Chrome instances to send and receive message data from servers. GCM Chrome API allows the Chrome apps or extensions to access the GCM service for the signed-in Chrome users. The service works even if an app or extension isn't currently running. For example, calendar updates could be pushed to users even when their calendar app isn't open.
To use both API and service, you must agree to the Google APIs Terms of Service and Google Cloud Platform Terms of Service.
This document describes how to set up and use GCM. For additional information see the reference documentation for the GCM Chrome API and the GCM Service. To get help with GCM or to give us feedback, please see Feedback.
Please note that GCM Chrome API is experimental. It is only available to Chrome users on the dev channel.
API Samples: Want to play with the code? Check out the gcm-notifications sample.
To use GCM for your app or extension, do the following:
At a glance, receiving a message works like this:
For more details, please see Receive messages.
At a glance, sending a message works like this:
For more details, please see Send messages.
To use the gcm service, you must declare the gcm
permission in
manifest.json
.
"permissions": [
"gcm", "storage", ...
]
Please note that the storage
permission is also provided here because the
sample codes below needs to persist some data via the
chrome.storage API.
Your app or extension needs to register with GCM servers before it can receive
messages. When an app or extension registers, it receives a registration ID.
This is achieved by calling $(ref:gcm.register) and specifying a list of senders
identified by project numbers from Google Developers Console. Your app or
extension should pass a callback function to verify that the registration was
successful. If successful, the received registration ID should be sent back to
your application server in a secure way, for example, via https. Otherwise, your
app or extension should handle the error identified by
chrome.runtime.lastError
and retry later.
If your app or extension wishes to receive messages from the different senders, it can call $(ref:gcm.register) again with the new sender list and the new registration ID will be returned.
function registerCallback(registrationId) {
if (chrome.runtime.lastError) {
// When the registration fails, handle the error and retry the
// registration later.
return;
}
// Send the registration ID to your application server.
sendRegistrationId(function(succeed) {
// Once the registration ID is received by your server,
// set the flag such that register will not be invoked
// next time when the app starts up.
if (succeed)
chrome.storage.local.set({registered: true});
});
}
function sendRegistrationId(callback) {
// Send the registration ID to your application server
// in a secure way.
}
chrome.runtime.onStartup.addListener(function() {
chrome.storage.local.get("registered", function(result) {
// If already registered, bail out.
if (result["registered"])
return;
// Up to 100 senders are allowed.
var senderIds = ["Your-Sender-ID"];
chrome.gcm.register(senderIds, registerCallback);
});
});
If your app or extension is installed in different profiles and/or in different Chrome instances, each of them will receive a different registration ID.
Your app or extension could call $(ref:gcm.unregister) to revoke the registration ID. The unregistration should only be done in rare cases, such as if your app or extension does not want to receive further messages, or the registration ID is suspected to be compromised.
function unregisterCallback() {
if (chrome.runtime.lastError) {
// When the unregistration fails, handle the error and retry
// the unregistration later.
return;
}
}
chrome.gcm.unregister(unregisterCallback);
Your app or extension is automatically unregistered from the GCM service when a user uninstalls it.
When your server sends a message to the user, it specifies all of the registration IDs that are related to that user and passes the message to the GCM service. GCM servers route the message to all instances of Chrome running apps or extensions with one of the registration IDs. If your app or extension has been installed in more than one profiles in a single Chrome instance, all of them can receive messages independently based on their unique registration IDs.
Messages from the server are delivered via the $(ref:gcm.onMessage) event. Your app or extension must register a handler to receive this event.
chrome.gcm.onMessage.addListener(function(message) {
// A message is an object with a data property that
// consists of key-value pairs.
});
As long as Chrome is running, even if the extension or app is not running, it is woken up to deliver a message.
To send messages upstream, your app or extension should call $(ref:gcm.send) with an object containing:
When the callback passed in $(ref:gcm.send) is called without runtime error, it does not mean that the message was already delivered to the GCM server. Rather, it means that it was queued for delivery. If the message fails to reach the destination within the specified TTL period, for example due to network error, the $(ref:gcm.onSendError) will be fired.
// Substitute your own sender ID here. This is the project
// number you got from the Google Developers Console.
var senderId = "Your-Sender-ID";
// Make the message ID unique across the lifetime of your app.
// One way to achieve this is to use the auto-increment counter
// that is persisted to local storage.
// Message ID is saved to and restored from local storage.
var messageId = 0;
chrome.storage.local.get("messageId", function(result) {
if (chrome.runtime.lastError)
return;
messageId = parseInt(result["messageId"]);
if (isNaN(messageId))
messageId = 0;
});
// Sets up an event listener for send error.
chrome.gcm.onSendError.addListener(sendError);
// Returns a new ID to identify the message.
function getMessageId() {
messageId++;
chrome.storage.local.set({messageId: messageId});
return messageId.toString();
}
function sendMessage() {
var message = {
messageId: getMessageId(),
destinationId: senderId + "@gcm.googleapis.com",
timeToLive: 86400, // 1 day
data: {
"key1": "value1",
"key2": "value2"
}
};
chrome.gcm.send(message, function(messageId) {
if (chrome.runtime.lastError) {
// Some error occurred. Fail gracefully or try to send
// again.
return;
}
// The message has been accepted for delivery. If the message
// can not reach the destination, onSendError event will be
// fired.
});
}
function sendError(error) {
console.log("Message " + error.messageId +
" failed to be sent: " + error.errorMessage);
}
GCM will store up to 100 non-collapsible messages. After that, all messages are discarded from GCM, and an event $(ref:gcm.onMessagesDeleted) will be fired, which tells the client that it falls behind. Your app or extension should respond by syncing with your application server to recover the discarded messages.
chrome.gcm.onMessagesDeleted.addListener(messagesDeleted);
function messagesDeleted() {
// All messages have been discarded from GCM. Sync with
// your application server to recover from the situation.
}
GCM messages are often a tickle, telling the app or extension to contact the
server for fresh data. In GCM, it's possible to create collapsible messages for
this situation, wherein new messages replace older ones. When a collapse key is
provided and multiple messages are queued up in the GCM servers for the same
user, only the last one with any given collapse key is delivered to your app or
extension. As a result the message
object passed to the $(ref:gcm.onMessage) event
will contain a collapseKey
field. For more details about sending collapsible
messages, please refer to GCM Advance
Topics.
To use the GCM service, you must publish your app in the Chrome Web Store.
An error could occur when a gcm API function is called. Your app or extension should check $(ref:runtime.lastError) for more information in your callback. The error code will also be passed as a parameter to $(ref:gcm.onSendError) event.
Here's a brief summary of the gcm errors:
You can provide feedback about Google Cloud Messaging and the gcm API through the Google Group GCM for Chrome Feedback. Use this group to ask for help, file bug reports, and request features.