Google Cloud Messaging for Chrome

If you are looking for the new Google Cloud Messaging API, please click here.

Google Cloud Messaging for Chrome (GCM) is a service for signed-in Chrome users that helps developers send message data from servers to their Chrome apps and extensions. The service is intended to wake up an app or extension, and/or alert a user. For example, calendar updates could be pushed to users even when their calendaring app isn't open.

This document describes how to set up and use GCM. For additional information see the reference documentation for the pushMessaging Chrome API and the GCM service. To get help with GCM or to give us feedback, see Feedback.

How push messaging works

At a glance, push messaging works like this:

  1. You upload your app or extension client to the Chrome Web Store.
  2. A user installs your app or extension.
  3. Your app or extension client requests the user's channel ID and sends this ID to your server.
  4. Your app or extension server sends a message to the push messaging service.
  5. The push messaging service routes the message to all instances of Chrome where the user is signed in.
  6. When the app or extension starts, it needs to register a handler to receive the pushMessaging.onMessage event.
  7. When the message arrives on the client, Chrome starts the app or extension, if it is not already running, and calls the registered handler.

Diving in a bit more, the Chrome Web Store assigns your newly published app or extension a unique app ID. When a user installs your app or extension, the client needs to call pushMessaging.getChannelId. The push messaging service returns a channel ID to the client; this ID is specifically linked to your app ID and to the user. Whatever method your client uses to send the channel ID to the server, it must be secured (https, for instance). For example, the client could send an XHR request to a RESTful API on your server.

As long as Chrome is running in the background or foreground, even if the extension or app is not running, it is woken up to deliver a message. For this to work, your app or extension must register a handler to receive the event, similar to how they’d register for launch events.

Your app/extension server is responsible for sending a push message to the service. In all push message requests, your server must include the user's channel ID and a valid OAuth 2.0 access token: the access token authorizes use of the service and the channel ID identifies the user and app to receive the message.

Any messages sent are delivered to all instances of that application installed in a Chrome profile signed in as that user. The most recent message sent on each subchannel is automatically queued for delivery to instances of Chrome which are not connected to the push messaging service at the time. If multiple messages are sent on one subchannel while Chrome is disconnected, then Chrome may only receive the last one sent when it reconnects.

Subchannels can also be used to implement priority schemes. For example, if you had an instant messaging app, requests for a phone call or video chat can go through immediately, instead of waiting for all the backed up chat messages to be cleared.

To Do Checklist

Here's a quick checklist of what you need to do to use the push messaging service (the remainder of this doc covers the steps in detail):

  1. Register your app or extension:
    • Create the client ID in the Google APIs Console.
    • Get the refresh token to set up authorization to use the service.
  2. Set up your app or extension to use the service:
    • Add the permission to the manifest.
    • Include a call to getChannelId for any user who is to receive a message.
    • Register a handler to receive the onMessage event.
  3. Publish your app in the Chrome Web Store.
  4. Use refresh token to get a valid access token.
  5. Send message to user.

Register app or extension

Create client ID

Complete the following steps to create the client ID:

  1. Login to the Google APIs Console using the same Google Account that you will use to upload your app.
  2. Create a new project by expanding the drop-down menu in the top-left corner and selecting the Create... menu item.
  3. Go to the "Services" navigation menu item and turn on the Google Cloud Messaging for Chrome API.
  4. Go to the "API Access" pane and click on the Create an OAuth 2.0 client ID... blue button.
  5. Enter the requested branding information, if needed
  6. For “Application type” select “Web application”.
  7. Click "more options" beside "Your site or hostname" and under "Authorized Redirect URIs", enter the following URL: https://developers.google.com/oauthplayground.
  8. Click "Create client ID" button.

The client ID and the client secret from this step are used in further steps. Be sure to keep the client ID and secret in a safe place, and don't expose them to outsiders.

Get refresh token

You need two types of OAuth 2.0 tokens to authorize each call to the push messaging service: the refresh token and the access token. The access token authorizes each call to the service; however, this token expires after about an hour. The refresh token is used to 'refresh' the access token over time. These tokens are scoped to only send messages on behalf of your application or extension and nothing else.

To get the refresh token and initial access token:

  1. Open an Incognito window in Chrome; this ensures that you are logged into the correct Google Account. If you only have one Google Account, you don't need to use an incognito window.
  2. Go to the OAuth 2.0 Playground.
  3. Click the OAuth 2.0 Configuration button in the top right corner.
  4. Check the box "Use your own OAuth credentials", enter the client ID and client secret, and click "Close".
  5. In the "Step 1" section, enter the scope https://www.googleapis.com/auth/gcm_for_chrome into the "Input your own scopes" text box and click "Authorize APIs" button.
  6. Assuming you are in Incognito mode, you should be redirected to the Google log in page. Login with the same Google Account that you will use to upload your app or extension to the Chrome Web Store.
  7. After successful log in, you are redirected to a page to authorize the scopes. Click "Allow access" button, redirecting you back to the OAuth 2.0 playground.
  8. In "Step 2", click "Exchange authorization code for tokens" button.

The refresh token never expires until you explicitly revoke access. You need to record and embed the refresh token in the app or extension server side.

Be careful: The refresh token should not be shown to anyone outside your organization; it should never be exposed on the client. If anyone gets your refresh token, they could potentially send messages as your server.

Set up app or extension

Add permission to manifest

To use the push messaging service, you must declare the pushMessaging permission in manifest.json:

"permissions": [
  "pushMessaging",
 ]

Get channel ID

Similar to an email address, the channel ID is used to identify and send messages to a specific user of your app or extension. Your app or extension needs to send this value to its application server so that the server can trigger push messages back. To get the user's channel ID, call pushMessaging.getChannelId. Use the callback function to send the channel ID back to your app or extension.

chrome.pushMessaging.getChannelId(boolean interactive, function ChannelIdCallback)

When the interactive flag is set to true, the user is asked to log in if they haven't already done so with a warning dialog that looks something like this: "You must log into Chrome for the Calendar extension to receive push messages. Log in now?"

To provide your users with a better experience, the interactive flag should be set to false the first time your app or extension calls getChannelId. Otherwise users will see the sign-in dialog with no context, even before they start your app or extension. If the first call fails because the user is not logged in, then getChannelId can be called again with the flag set to true. You should provide a context dialog before the second call is made.

Register message event handler

Whenever Chrome receives a pushed message for an application/extension, it delivers the push message to the app or extension client. Your app or extension must register a handler to receive the event whenever the app or extension starts up, similar to how they’d register for launch events. This gets added to the background.js, for example:

function setupPush() {
  chrome.pushMessaging.onMessage.addListener(messageCallback);
}

The app or extension need not be running when the message arrives; the handler can be registered after the message arrives.

Publish your app

To use the push messaging service, you must publish your app in the Chrome Web Store.

Send messages

Get new access token

You need a valid access token to push messages to your app or extension. To obtain a new access token, make an HTTPS POST that includes your client ID and refresh token. Using OAuth 2.0 for Web Server Applications describes this in greater detail. A sample request would like something like this:

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded

client_id=291796959215.apps.googleusercontent.com&
client_secret=0bKUtXN6ykk7Mj1lQxoBZ2mh&
refresh_token=1%wMfyZvGcCxMSNEX4iTRdE0H1_Yt0wvImBz_iCuXF-UM&
grant_type=refresh_token

A response from such a request is shown below:

{
  "access_token":"1/fFBGRNJru1FQd44AzqT3Zg",
  "expires_in":3920,
  "token_type":"Bearer"
}

Reminder: You should cache the access token for use until it expires. There is a rate limit on how often you can ask for access tokens. You may find yourself locked out of sending messages for awhile if you get a new access token every time you send a push message.

Send message to user

Send a POST body that includes the channel ID and subchannel ID along with the message payload to the API endpoint https://www.googleapis.com/gcm_for_chrome/v1/messages. Here's what a sample HTTP call would look like:

POST /gcm_for_chrome/v1/messages
Host: www.googleapis.com
Content-Type: application/json
Authorization: Bearer 1/fFBGRNJru1FQd44AzqT3Zg

{
  "channelId": "08144192009958038014/aaaaaaaaaabbbbbbbbbbcccccccccc",
  "subchannelId": "0",
  "payload": "Thanks for installing my app!"
}

Messages can be coalesced. If you send multiple messages on subchannel 1, for instance, you may only see the last message and its payload. Also, payloads can sometimes be dropped; treat a payload as an optimization. You can always go back to the server to check for the contents of previous messages and to get data if the payload is not present.

Here's a simple example that shows a push message as a text notification when it arrives:

function showPushMessage(message) {
  var notification = window.webkitNotifications.createNotification(
    '', 'New notification', message.payload + " [" + message.subchannelId + "]");
  notification.show();
}

You need to add the "notifications" permission to manifest.json to use text notifications (see Desktop Notifications):

"permissions": [
  "pushMessaging",
  "notifications"
 ]

Error reference

Push messaging error codes indicate whether the push request was accepted or rejected. Rejection reasons include sender errors (for example, malformed message), permission errors (for example, revoked push messaging token), and operational errors (for example, push messaging service is currently down).

Here's a brief summary of the push messaging errors:

  • Channel ID is invalid.
  • Subchannel is invalid (four subchannels available; subchannel value must be 0, 1, 2, or 3).
  • Payload is too long (must be 256 bytes or less).
  • Daily message quota exceeded (10,000 message requests allowed per day).
  • Google Account calling the push messaging service does not own the app or extension.
  • An internal error has occurred. This indicates something went wrong on the Google server side (for example, some backend not working or errors in the HTTP post such as a missing access token).

Testing

Testing locally

To test push messaging locally:

  1. Package a test version of your app or extension on the Extensions management page (chrome://extensions). Your app or extension doesn't need to be running; it just needs to be installed.
  2. Get the channel ID at install time using app.runtime.onLaunched.
  3. Use that channel ID on the server to send a test push message through the system. If all goes well, your app or extension should start and you should receive the test push message.

Testing in the cloud

To test push messaging in the cloud, you must first make sure that the app or extension you are testing passes an ownership check. The Push Messaging server checks that the ID of an app or extension that calls the pushMessaging API matches the ID of the app or extension in the Chrome Web Store. This ownership check is designed to prevent people from sending messages to your app or extension without your permission. If your app or extension attempts to use the pushMessaging API and the ownership check fails, it will receive HTTP status code 500 (Internal Server Error).

One circumstance in which the ownership check commonly fails is when you are developing an app and you run the app without uploading it and re-downloading it from the Chrome Web Store. In this situation your app may not have a key field in its manifest.json file. The key field gives an app its Chrome Web Store ID (a 32 character alphabetic code, such as "bafimiidcfafikaonocgmmcpbbhfjjik"). If you run a version of your app without a key, the app will use a randomly generated ID that will not match the app's ID in the Chrome Web Store. For example, if you upload your app to the Chrome Web Store from the directory original_app_dir, then download the app and unpack it to downloaded_app_dir, and then run the exact same app as an unpacked extension from original_app_dir, the manifest.json file of the app in original_app_dir would not have the downloaded key, and the app's ID would appear to be different than the ID of the downloaded app.

To test push messaging in the cloud:

  1. Publish your app or extension to the Chrome Web Store.
  2. Determine the Chrome Web Store ID of your app or extension. The Chrome Web Store ID is in the URL of any dashboard or Chrome Web Store page that's dedicated to your app or extension. For example, the URL https://chrome.google.com/extensions/detail/aaaaaaaaaabbbbbbbbbbcccccccccc?hl=en has the ID aaaaaaaaaabbbbbbbbbbcccccccccc.
  3. Install your app or extension from the Chrome Web Store.
  4. Get the key from the installed app or extension:
    1. Go to your user data directory.
    2. Look in the file Default/Extensions/<ID>/<versionString>/manifest.json.
    3. Copy the key field.
  5. Paste the key field into manifest.json in the test version of your app or extension.
  6. Install a test version of your app or extension on the Extensions management page (chrome://extensions).

Each time you reload your app or extension for testing, you need to check that the key is present in the manifest file. And anytime you wish to update the published version in the Chrome Web Store, you need to remove the key because the Store does not currently allow manifests with keys.

Feedback

You can provide feedback about Google Cloud Messaging and the pushMessaging API through the Google Group GCM for Chrome feedback. Use this group to ask for help, file bug reports, and request features.