Home | History | Annotate | Download | only in articles
      1 <meta name="doc-family" content="apps">
      2 <h1>Google Cloud Messaging for Chrome</h1>
      3 
      4 <p>
      5 Google Cloud Messaging for Chrome (GCM) is a service
      6 for signed-in Chrome users
      7 that helps developers send message data from servers
      8 to their Chrome apps and extensions.
      9 The service is intended to wake up an app or extension,
     10 and/or alert a user.
     11 For example, calendar updates could be pushed to users
     12 even when their calendaring app isn't open.
     13 </p>
     14 
     15 <p>This document describes how to set up and use GCM.
     16 For additional information see the reference documentation
     17 for the <a href="pushMessaging.html">pushMessaging Chrome API</a> and the
     18 <a href="gcm_server.html">GCM service</a>.
     19 To get help with GCM or to give us feedback, see <a href="#feedback">Feedback</a>.
     20 </p>
     21 
     22 <h2 id="one">How push messaging works</h2>
     23 
     24 <p>
     25 At a glance, push messaging works like this:
     26 </p>
     27 
     28 <ol>
     29   <li>You upload your app or extension client to the Chrome Web Store.</li>
     30   <li>A user installs your app or extension.</li>
     31   <li>Your app or extension client requests the user's channel ID
     32   and sends this ID to your server.</li>
     33   <li>Your app or extension server sends a message
     34   to the push messaging service.</li>
     35   <li>The push messaging service routes the message
     36   to all instances of Chrome where the user is signed in.</li>
     37   <li>When the app or extension starts,
     38   it needs to register a handler to receive the
     39   $ref:pushMessaging.onMessage event.</li>
     40   <li>When the message arrives on the client,
     41   Chrome starts the app or extension, if it is not already running,
     42   and calls the registered handler.</li>
     43 </ol>
     44 
     45 <p>
     46 Diving in a bit more,
     47 the Chrome Web Store assigns your newly published app
     48 or extension a unique app ID.
     49 When a user installs your app or extension,
     50 the client needs to call $ref:pushMessaging.getChannelId.
     51 The push messaging service returns a channel ID to the client;
     52 this ID is specifically linked to your app ID and to the user.
     53 Whatever method your client uses to send the channel ID to the server,
     54 it must be secured (https, for instance).
     55 For example,
     56 the client could send an XHR request
     57 to a RESTful API on your server.
     58 </p>
     59 
     60 <p>
     61 As long as Chrome is running in the background or foreground,
     62 even if the extension or app is not running,
     63 it is woken up to deliver a message.
     64 For this to work,
     65 your app or extension must register a handler to receive the event,
     66 similar to how theyd register for launch events.
     67 </p>
     68 
     69 <p>
     70 Your app/extension server is responsible
     71 for sending a push message to the service.
     72 In all push message requests,
     73 your server must include the user's channel ID
     74 and a valid OAuth 2.0 access token:
     75 the access token authorizes use of the service and
     76 the channel ID identifies the user and app to receive the message.
     77 </p>
     78 
     79 <p>
     80 Any messages sent are delivered
     81 to all instances of that application installed 
     82 in a Chrome profile signed in as that user.
     83 The most recent message sent on each subchannel is automatically queued
     84 for delivery to instances of Chrome which are not connected to the push
     85 messaging service at the time. If multiple messages are sent on one subchannel
     86 while Chrome is disconnected, then Chrome may only receive the last one sent
     87 when it reconnects.
     88 </p>
     89 
     90 <p>
     91 Subchannels can also be used to implement priority schemes.
     92 For example,
     93 if you had an instant messaging app,
     94 requests for a phone call or video chat can go through immediately,
     95 instead of waiting for all the backed up chat messages to be cleared.
     96 </p>
     97 
     98 <h2 id="checklist">To Do Checklist</h2>
     99 
    100 <p>
    101 Here's a quick checklist of what you need to do
    102 to use the push messaging service
    103 (the remainder of this doc covers the steps in detail):
    104 </p>
    105 
    106 <ol>
    107   <li>Register your app or extension:
    108     <ul>
    109       <li>Create the client ID in the Google APIs Console.</li>
    110       <li>Get the refresh token to set up authorization to use the service.</li>
    111     </ul>
    112   </li>
    113   <li>Set up your app or extension to use the service:
    114   	<ul>
    115   	  <li>Add the permission to the manifest.</li>
    116   	  <li>Include a call to <code>getChannelId</code>
    117       for any user who is to receive a message.</li>
    118   	  <li>Register a handler to receive the
    119   	  <code>onMessage</code> event.</li>	
    120   	</ul>
    121    </li>
    122   <li>Publish your app in the Chrome Web Store. </li>
    123   <li>Use refresh token to get a valid access token.</li>
    124   <li>Send message to user.</li>
    125 </ol>
    126 
    127 <h2 id="two">Register app or extension</h2>
    128 
    129 <h3 id="clientid">Create client ID</h3>
    130 
    131 <p>
    132 Complete the following steps to create the client ID:
    133 </p>
    134 
    135 <ol>
    136   <li>Login to the
    137   <a href="https://code.google.com/apis/console/">Google APIs Console</a>
    138   using the same Google Account that you will use to upload your app.</li>
    139   <li> Create a new project by expanding the drop-down menu in the top-left corner
    140   and selecting the <strong>Create...</strong> menu item.</li>
    141   <li>Go to the "Services" navigation menu item and
    142   turn on the <strong>Google Cloud Messaging for Chrome API</strong>.</li>
    143   <li>Go to the "API Access" pane and click on the
    144   <strong>Create an OAuth 2.0 client ID...</strong> blue button.</li>
    145   <li>Enter the requested branding information, if needed</li>
    146   <li>For Application type select Web application.</li>
    147   <li>Click "more options" beside "Your site or hostname"
    148   and under "Authorized Redirect URIs", enter the following URL:
    149   <code>https://developers.google.com/oauthplayground</code>.</li>
    150   <li>Click "Create client ID" button.</li>
    151 </ol>
    152 
    153 <p>
    154 The client ID and the client secret
    155 from this step are used in further steps.
    156 Be sure to keep the client ID and secret in a safe place,
    157 and don't expose them to outsiders.
    158 </p>
    159 
    160 <h3 id="refresh">Get refresh token</h3>
    161 
    162 <p>
    163 You need two types of OAuth 2.0 tokens to authorize
    164 each call to the push messaging service:
    165 the refresh token and the access token.
    166 The access token authorizes each call to the service;
    167 however, this token expires after about an hour.
    168 The refresh token is used
    169 to 'refresh' the access token over time.
    170 These tokens are scoped to only send messages on behalf
    171 of your application or extension and nothing else.
    172 </p>
    173 
    174 <p>
    175 To get the refresh token and initial access token:
    176 </p>
    177 
    178 <ol>
    179   <li>Open an Incognito window in Chrome;
    180   this ensures that you are logged into the correct Google Account.
    181   If you only have one Google Account,
    182   you don't need to use an incognito window.</li>
    183   <li>Go to the
    184   <a href="https://developers.google.com/oauthplayground/">OAuth 2.0 Playground</a>.</li>
    185   <li>Click the <img src="{{static}}/images/gearsicon.png" width="29" height="23" align="middle"/>
    186   <strong>OAuth 2.0 Configuration</strong> button in the top right corner.</li>
    187   <li>Check the box "Use your own OAuth credentials",
    188   enter the client ID and client secret, and click "Close".</li>
    189   <li>In the "Step 1" section, enter the scope
    190   <code>https://www.googleapis.com/auth/gcm_for_chrome</code> into the
    191   "Input your own scopes" text box and click "Authorize APIs" button.</li>
    192   <li>Assuming you are in Incognito mode,
    193   you should be redirected to the Google log in page.
    194   Login with the same Google Account that you will use to upload your app or extension
    195   to the Chrome Web Store.</li>
    196   <li>After successful log in, you are redirected to a page to authorize the scopes.
    197   Click "Allow access" button, redirecting you back to the OAuth 2.0 playground.</li>
    198   <li>In "Step 2", click "Exchange authorization code for tokens" button.</li>
    199 </ol>
    200 
    201 <p>
    202 The refresh token never expires until you explicitly revoke access.
    203 You need to record and embed the refresh token in the app or extension server side.
    204 </p>
    205 
    206 <p class="caution">
    207 <b>Be careful:</b>
    208 The refresh token should not be shown to anyone outside your organization;
    209 it should never be exposed on the client.
    210 If anyone gets your refresh token,
    211 they could potentially send messages as your server.
    212 </p>
    213 
    214 <h2 id="three">Set up app or extension</h2>
    215 
    216 <h3 id="manifest">Add permission to manifest</h3>
    217 
    218 <p>
    219 To use the push messaging service,
    220 you must declare the <code>pushMessaging</code>
    221 permission in <code>manifest.json</code>:
    222 </p>
    223 
    224 <pre data-filename="manifest.json">
    225 "permissions": [
    226   "pushMessaging",
    227  ]
    228 </pre>
    229 
    230 <h3 id="channelid">Get channel ID</h3>
    231 
    232 <p>
    233 Similar to an email address,
    234 the channel ID is used to identify and send messages
    235 to a specific user of your app or extension.
    236 Your app or extension needs to send this value
    237 to its application server so that the server
    238 can trigger push messages back.
    239 To get the user's channel ID,
    240 call $ref:pushMessaging.getChannelId.
    241 Use the callback function
    242 to send the channel ID back to your app or extension.
    243 </p>
    244 
    245 <pre>
    246 chrome.pushMessaging.getChannelId(boolean interactive, function ChannelIdCallback)
    247 </pre>
    248 
    249 <p>
    250 When the <code>interactive</code> flag is set to true,
    251 the user is asked to log in if they haven't already done so
    252 with a warning dialog that looks something like this:
    253 "You must log into Chrome for the Calendar extension to receive push messages. 
    254 Log in now?"
    255 </p>
    256 
    257 <p>
    258 To provide your users with a better experience,
    259 the interactive flag should be set to false the first time
    260 your app or extension calls <code>getChannelId</code>.
    261 Otherwise users will see the sign-in dialog
    262 with no context,
    263 even before they start your app or extension.
    264 If the first call fails because the user is not logged in,
    265 then <code>getChannelId</code> can be called again
    266 with the flag set to true.
    267 You should provide a context dialog
    268 before the second call is made.
    269 </p>
    270 
    271 <h3 id="registerPush">Register message event handler</h3>
    272 
    273 <p>
    274 Whenever Chrome receives a pushed message for an application/extension,
    275 it delivers the push message to the app or extension client.
    276 Your app or extension must register a handler to receive the event
    277 whenever the app or extension starts up,
    278 similar to how theyd register for launch events.
    279 This gets added to the <code>background.js</code>, for example:
    280 </p>
    281 
    282 <pre>
    283 function setupPush() {
    284   chrome.pushMessaging.onMessage.addListener(messageCallback);
    285 }
    286 </pre>
    287 
    288 <p>
    289 The app or extension need not be running when the message arrives;
    290 the handler can be registered after the message arrives.
    291 </p>
    292 
    293 <h2 id="store">Publish your app</h2>
    294 
    295 {{^is_apps}}
    296 <p>
    297 To use the push messaging service,
    298 you must publish your extension in the
    299 <a href="https://developers.google.com/chrome/web-store/docs/get_started_simple">Chrome Web Store</a>.
    300 </p>
    301 {{/is_apps}}
    302 
    303 {{?is_apps}}
    304 <p>
    305 To use the push messaging service,
    306 you must publish your app in the
    307 <a href="https://developers.google.com/chrome/web-store/docs/get_started_simple">Chrome Web Store</a>.
    308 </p>
    309 {{/is_apps}}
    310 
    311 <h2 id="five">Send messages</h2>
    312 
    313 <h3 id="access">Get new access token</h3>
    314 
    315 <p>
    316 You need a valid access token to push messages
    317 to your app or extension.
    318 To obtain a new access token,
    319 make an <code>HTTPS POST</code>
    320 that includes your client ID and refresh token.
    321 <a href="https://developers.google.com/accounts/docs/OAuth2WebServer">Using OAuth 2.0 for
    322 	Web Server Applications</a>
    323 describes this in greater detail.
    324 A sample request would like something like this:
    325 </p>
    326 
    327 <pre>
    328 POST /o/oauth2/token HTTP/1.1
    329 Host: accounts.google.com
    330 Content-Type: application/x-www-form-urlencoded
    331 
    332 client_id=291796959215.apps.googleusercontent.com&
    333 client_secret=0bKUtXN6ykk7Mj1lQxoBZ2mh&
    334 refresh_token=1%wMfyZvGcCxMSNEX4iTRdE0H1_Yt0wvImBz_iCuXF-UM&
    335 grant_type=refresh_token
    336 </pre>
    337 
    338 <p>
    339 A response from such a request is shown below:
    340 </p>
    341 
    342 <pre>
    343 {
    344   "access_token":"1/fFBGRNJru1FQd44AzqT3Zg",
    345   "expires_in":3920,
    346   "token_type":"Bearer"
    347 }
    348 </pre>
    349 
    350 <p class="note">
    351 <b>Reminder:</b>
    352 You should cache the access token for use
    353 until it expires.
    354 There is a rate limit on how often you can ask for access tokens.
    355 You may find yourself locked out of sending messages for awhile
    356 if you get a new access token every time you send a push message.
    357 </p>
    358 
    359 <h3 id="message">Send message to user</h3>
    360 
    361 <p>
    362 Send a <code>POST</code> body that includes the channel ID and subchannel ID
    363 along with the message payload to the API endpoint
    364 <code>https://www.googleapis.com/gcm_for_chrome/v1/messages</code>.
    365 Here's what a sample HTTP call would look like:
    366 </p>
    367 
    368 <pre>
    369 POST /gcm_for_chrome/v1/messages
    370 Host: www.googleapis.com
    371 Content-Type: application/json
    372 Authorization: Bearer 1/fFBGRNJru1FQd44AzqT3Zg
    373 
    374 {
    375   'channelId': '08144192009958038014/aaaaaaaaaabbbbbbbbbbcccccccccc',
    376   'subchannelId': '0', 
    377   'payload': 'Thanks for installing my app!'	
    378 }
    379 </pre>
    380 
    381 <p>
    382 Messages can be coalesced.
    383 If you send multiple messages on subchannel 1, for instance,
    384 you may only see the last message and its payload.
    385 Also, payloads can sometimes be dropped;
    386 treat a payload as an optimization.
    387 You can always go back to the server to check
    388 for the contents of previous messages and
    389 to get data if the payload is not present.
    390 </p>
    391 
    392 <p>Here's a simple example that shows a push message
    393 as a text notification when it arrives:
    394 </p>
    395 
    396 <pre>
    397 function showPushMessage(message) {
    398   var notification = window.webkitNotifications.createNotification(
    399     '', 'New notification', message.payload + " [" + message.subchannelId + "]");
    400   notification.show();
    401 }
    402 </pre>
    403 
    404 <p>
    405 You need to add the "notifications" permission
    406 to <code>manifest.json</code>
    407 to use text notifications
    408 (see <a href="desktop_notifications.html">Desktop Notifications</a>):
    409 </p>
    410 
    411 <pre data-filename="manifest.json">
    412 "permissions": [
    413   "pushMessaging",
    414   "notifications"
    415  ]
    416 </pre>
    417 
    418 <h2 id="six">Error reference</h2>
    419 
    420 <p>
    421 Push messaging error codes indicate whether the push request was accepted or rejected. 
    422 Rejection reasons include sender errors (for example, malformed message),
    423 permission errors (for example, revoked push messaging token),
    424 and operational errors (for example, push messaging service is currently down).
    425 </p>
    426 
    427 <p>
    428 Here's a brief summary of the push messaging errors:
    429 </p>
    430 
    431 <ul>
    432   <li>Channel ID is invalid.</li>
    433   <li>Subchannel is invalid (four subchannels available;
    434   subchannel value must be 0, 1, 2, or 3).</li>
    435   <li>Payload is too long (must be 256 bytes or less).</li>
    436   <li>Daily message quota exceeded (10,000 message requests allowed per day).</li>
    437   <li>Google Account calling the push messaging service does not own the app or extension.</li>
    438   <li>An internal error has occurred.
    439   This indicates something went wrong on the Google server side
    440   (for example, some backend not working
    441   or errors in the HTTP post such as a missing access token).</li>
    442 </ul>
    443 
    444 <h2 id="test">Testing</h2>
    445 
    446 <h3 id="test-local">Testing locally</h3>
    447 
    448 <p>
    449 To test push messaging locally:
    450 </p>
    451 
    452 <ol>
    453   <li><a href="packaging.html">Package</a> a test version of
    454   your app or extension on the Extensions management page
    455   (chrome://extensions).
    456   Your app or extension doesn't need to be running; it just needs
    457   to be installed.</li>
    458 
    459   <li>Get the channel ID at install time using
    460   {{?is_apps}}$ref:app.runtime.onLaunched.{{/is_apps}}
    461   {{^is_apps}}$ref:runtime.onInstalled.{{/is_apps}}</li>
    462 
    463   <li>Use that channel ID on the server to send a test
    464   push message through the system.
    465   If all goes well,
    466   your app or extension should start
    467   and you should receive the test push message.
    468   </li>
    469 </ol>
    470 
    471 <h3 id="test-cloud">Testing in the cloud</h3>
    472 
    473 <p>To test push messaging in the cloud, you must first make sure that the
    474 app or extension you are testing passes an ownership check.
    475 The Push Messaging server checks that the ID of an app or extension
    476 that calls the pushMessaging API matches the ID of the app or extension
    477 in the Chrome Web Store. This ownership check is designed to prevent people
    478 from sending messages to your app or extension without your permission.
    479 If your app or extension attempts to use the pushMessaging API and
    480 the ownership check fails, it will receive
    481 HTTP status code 500 (Internal Server Error).
    482 </p>
    483 
    484 <p>
    485 One circumstance in which the ownership check commonly fails is when you are
    486 developing an app and you run the app without uploading it and re-downloading
    487 it from the Chrome Web Store. In this situation your app may not have a
    488 <a href="manifest/key.html">key</a> field in its manifest.json file.
    489 The <code>key</code> field gives an app its Chrome Web Store ID
    490 (a 32 character alphabetic code, such as "bafimiidcfafikaonocgmmcpbbhfjjik").
    491 If you run a version of your app without a key, the app will use a
    492 randomly generated ID that will not match the app's ID in the Chrome Web Store.
    493 For example, if you upload your app to the Chrome Web Store from the directory
    494 original_app_dir, then download the app and unpack it to downloaded_app_dir,
    495 and then run the exact same app as an unpacked extension from original_app_dir,
    496 the manifest.json file of the app in original_app_dir would not have
    497 the downloaded key, and the app's ID would appear to be different than
    498 the ID of the downloaded app.
    499 </p>
    500 
    501 <p>
    502 To test push messaging in the cloud:
    503 </p>
    504 
    505 <ol>
    506   <li>Publish your app or extension to the Chrome Web Store.</li>
    507 
    508   <li>Determine the Chrome Web Store ID of your app or extension.
    509   The Chrome Web Store ID is in the URL of any dashboard
    510   or Chrome Web Store page that's dedicated to your app or extension.
    511   For example, the URL
    512   <code>https://chrome.google.com/extensions/detail/aaaaaaaaaabbbbbbbbbbcccccccccc?hl=en</code>
    513   has the ID <code>aaaaaaaaaabbbbbbbbbbcccccccccc</code>.</li>
    514 
    515 
    516   <li>Install your app or extension from the Chrome Web Store.</li>
    517   
    518   <li>Get the key from the installed app or extension:
    519 
    520     <ol style="list-style-type: lower-alpha;">
    521       <li>Go to your
    522       <a href="http://www.chromium.org/user-experience/user-data-directory">user data directory</a>.
    523       </li>
    524 
    525       <li>Look in the file <code>Default/Extensions/&lt;<i>ID</i>&gt;/&lt;<i>versionString</i>&gt;/manifest.json</code>.
    526       </li>
    527 
    528       <li>Copy the key field.</li>
    529     </ol>
    530   </li>
    531 
    532   <li>Paste the key field into manifest.json in
    533   the test version of your app or extension.</li>
    534 
    535   <li>Install a test version of your app or extension on the
    536   Extensions management page (chrome://extensions).</li>
    537 </ol>
    538 
    539 <p>
    540 Each time you reload your app or extension for testing,
    541 you need to check that the key is present in the manifest file.
    542 And anytime you wish to update the published version in the Chrome Web Store,
    543 you need to remove the key because the Store does not currently allow manifests
    544 with keys.
    545 </p>
    546 
    547 <h2 id="feedback">Feedback</h2>
    548 
    549 <p>You can provide feedback about Google Cloud Messaging
    550 and the pushMessaging API through the Google Group
    551 <a target="_blank" href="https://groups.google.com/forum/#!forum/gcm-for-chrome-feedback">GCM for Chrome feedback</a>. 
    552 Use this group to ask for help, file bug reports, and request features.</p>
    553