Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(52)

Side by Side Diff: chrome/common/extensions/docs/templates/articles/cloudMessagingV2.html

Issue 145443002: GCM for Chrome documentation (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Created 6 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 <meta name="doc-family" content="apps">
2 <h1 id="gcm">Google Cloud Messaging</h1>
3
4 <p>Google Cloud Messaging (GCM) is a service for both Android-powered device and
5 Chrome instances to send and receive message data from servers. <a href="gcm.htm l">GCM Chrome
6 API</a> allows the Chrome apps or extensions to access the GCM
7 service for the signed-in Chrome users. The service works even if an app or
8 extension isn't currently running. For example, calendar updates could be pushed
9 to users even when their calendar app isn't open. </p>
10
11 <p>To use both API and service, you must agree to the <a href="https://developer s.google.com/terms/">Google APIs Terms of
12 Service</a> and <a href="https://developers.google.com/cloud/terms/">Google Clou d Platform Terms
13 of Service</a>.</p>
14
15 <p>This document describes how to set up and use GCM. For additional information
16 see the reference documentation for the <a href="gcm.html">GCM Chrome API</a> an d
17 the <a href="http://developer.android.com/google/gcm/index.html">GCM Service</a> . To get
18 help with GCM or to give us feedback, please see
19 <a href="#feedback">Feedback</a>.</p>
20
21 <p>Please note that GCM Chrome API is experimental. It is only available to Chro me
22 users on the dev channel.</p>
23
24 <h2 id="enable_gcm">Enable GCM</h2>
25
26 <p>To use GCM for your app or extension, do the following:</p>
27
28 <ol>
29 <li>Upload your app or extension client to the <a href="https://developers.googl e.com/chrome/web-store/docs/publish">Chrome Web
30 Store</a>.</li>
31 <li>A user installs your app or extension.</li>
32 <li>Your app or extension client requests a registration ID using $ref:gcm.regis ter
33 function and sends this ID to your server together with information
34 identifying the user. For more details, please see <a href="#obtain_registration _id">Obtain registration
35 ID</a>.</li>
36 </ol>
37
38 <h2 id="receive_a_message">Receive a message</h2>
39
40 <p>At a glance, receiving a message works like this:</p>
41
42 <ol>
43 <li>Your app or extension client should register a handler to receive the
44 $ref:gcm.onMessage event.</li>
45 <li>When your server sends a message to the user, it specifies all of the
46 registration IDs that are related to that user and passes the message to the
47 GCM service.</li>
48 <li>GCM servers route the message to all instances of Chrome running apps or
49 extensions with one of the registration IDs.</li>
50 <li>When the message arrives on the client, Chrome starts the app or extension,
51 if it is not already running, and calls the registered handler to process the
52 message.</li>
53 </ol>
54
55 <p>For more details, please see <a href="#receive_messages">Receive messages</a> .</p>
56
57 <h2 id="send_a_message">Send a message</h2>
58
59 <p>At a glance, sending a message works like this:</p>
60
61 <ol>
62 <li>Your app or extension generates a unique message ID, so that it is possible
63 to find out which message failed to be queued or delivered.</li>
64 <li>Your app or extension calls $ref:gcm.send function with an object containing
65 message ID, destination ID that identifies the server, and data that consist
66 of a list of key value pairs. In this step you can also provide an optional
67 time-to-live for the message.</li>
68 <li>The callback passed to $ref:gcm.send function will be called to notify the
69 result. Your app or extension should check $ref:runtime.lastError to find out if
70 the message has been successfully queued for delivery. Please refer to <a href=" #error_reference">Error
71 reference</a> for possible error codes that could be
72 returned.</li>
73 <li>In cases that the queued message could not be delivered to the GCM server,
74 like network error, a $ref:gcm.onSendError event will be fired. Your app or
75 extension can listen to this event and react to it, e.g. by trying to resend
76 the message. Please refer to <a href="#error_reference">Error reference</a> for
77 possible error codes that could be returned.</li>
78 </ol>
79
80 <p>For more details, please see <a href="#send_messages">Send messages</a>.</p>
81
82 <h2 id="set_up_project">Set up project</h2>
83
84 <h3 id="create_google_api_project">Create Google API project</h3>
85
86 <ol>
87 <li>Login to the <a href="https://cloud.google.com/console/project">Google Devel opers
88 Console</a> using the same Google <br>
89 Account that you will use to upload your app or extension.</li>
90 <li>If you haven't created an API project yet, click <strong>Create Project</str ong>.</li>
91 <li>Supply a project name and click <strong>Create</strong>.</li>
92 <li>Once the project has been created, a page appears that displays your project
93 number. For example, <strong>Project Number: 670330094152</strong>.</li>
94 <li>Copy down your project number. You will use it later on as the GCM sender ID .</li>
95 </ol>
96
97 <h3 id="enable_the_gcm_service">Enable the GCM service</h3>
98
99 <ol>
100 <li>In the sidebar on the left, select <strong>APIs &amp; auth</strong>.</li>
101 <li>In the displayed list of APIs, turn the <strong>Google Cloud Messaging for
102 Android</strong> toggle to ON.</li>
103 </ol>
104
105 <h2 id="set_up_chrome_app_or_extension">Set up Chrome App or Extension</h2>
106
107 <h3 id="add_permission_to_manifest">Add permission to manifest</h3>
108
109 <p>To use the gcm service, you must declare the <code>gcm</code> permission in
110 <code>manifest.json</code>.</p>
111
112 <pre data-filename="manifest.json"><code>
113 "permissions": [
114 "gcm", "storage", ...
115 ]
116 </code></pre>
117
118 <p>Please note that the <code>storage</code> permission is also provided here be cause the
119 sample codes below needs to persist some data via the
120 <a href="storage.html">chrome.storage</a> API.</p>
121
122 <h2 id="write_chrome_app_or_extension">Write Chrome App or Extension</h2>
123
124 <h3 id="obtain_registration_id">Obtain registration ID</h3>
125
126 <p>Your app or extension needs to register with GCM servers before it can receiv e
127 messages. When an app or extension registers, it receives a registration ID.
128 This is achieved by calling $ref:gcm.register and specifying a list of senders
129 identified by project numbers from Google Developers Console. Your app or
130 extension should pass a callback function to verify that the registration was
131 successful. If successful, the received registration ID should be sent back to
132 your application server in a secure way, for example, via https. Otherwise, your
133 app or extension should handle the error identified by
134 <code>chrome.runtime.lastError</code> and retry later.</p>
135
136 <p>If your app or extension wishes to receive messages from the different sender s,
137 it can call $ref:gcm.register again with the new sender list and the new
138 registration ID will be returned.</p>
139
140 <pre data-filename="background.js"><code>
141 function registerCallback(registrationId) {
142 if (chrome.runtime.lastError) {
143 // When the registration fails, handle the error and retry the
144 // registration later.
145 return;
146 }
147
148 // Send the registration ID to your application server.
149 sendRegistrationId(function(succeed) {
150 // Once the registration ID is received by your server,
151 // set the flag such that register will not be invoked
152 // next time when the app starts up.
153 if (succeed)
154 chrome.storage.local.set({registered: true});
155 });
156 }
157
158 function sendRegistrationId(callback) {
159 // Send the registration ID to your application server
160 // in a secure way.
161 }
162
163 chrome.runtime.onStartup.addListener(function() {
164 chrome.storage.local.get("registered", function(result) {
165 // If already registered, bail out.
166 if (result["registered"])
167 return;
168
169 // Up to 100 senders are allowed.
170 var senderIds = ["Your-Sender-ID"];
171 chrome.gcm.register(senderIds, registerCallback);
172 });
173 });
174 </code></pre>
175
176 <p>If your app or extension is installed in different profiles and/or in differe nt
177 Chrome instances, each of them will receive a different registration ID.</p>
178
179 <p>Your app or extension is automatically unregistered from the GCM service when a
180 user uninstalls it. You can't unregister using the GCM API.</p>
181
182 <h3 id="receive_messages">Receive messages</h3>
183
184 <p>When your server sends a message to the user, it specifies all of the
185 registration IDs that are related to that user and passes the message to the GCM
186 service. GCM servers route the message to all instances of Chrome running apps
187 or extensions with one of the registration IDs. If your app or extension has
188 been installed in more than one profiles in a single Chrome instance, all of
189 them can receive messages independently based on their unique registration IDs.< /p>
190
191 <p>Messages from the server are delivered via the $ref:gcm.onMessage event. Your app
192 or extension must register a handler to receive this event.</p>
193
194 <pre data-filename="background.js"><code>
195 chrome.gcm.onMessage.addListener(function(message) {
196 // A message is an object with a data property that
197 // consists of key-value pairs.
198 });
199 </code></pre>
200
201 <p>As long as Chrome is running, even if the extension or app is not running, it is
202 woken up to deliver a message.</p>
203
204 <h3 id="send_messages">Send messages</h3>
205
206 <p>To send messages upstream, your app or extension should call $ref:gcm.send wi th an
207 object containing:</p>
208
209 <ul>
210 <li>Message ID that identifies the message when it fails to be queued or
211 delivered. The message ID can be any kind of string. However, it is
212 recommended to stay unique across the lifetime of your app or extension, even
213 after it restarts. If you use the same message ID, there may be a chance that
214 the previous message gets overridden. If an auto-increment counter is used to
215 create the message ID, your app or extension should persist the counter value
216 via <a href="storage.html">chrome.storage</a> API and restore it when the app
217 reloads.</li>
218 <li>Destination ID that identifies the server. This is the project number from t he
219 Google Developers Console plus the suffix "@gcm.googleapis.com".</li>
220 <li>Data that consist of a list of string-to-string key value pairs (up to 4KB
221 total).</li>
222 <li>Time-to-live (TTL, optional). This property value must be a duration from 0 to
223 2,419,200 seconds (4 weeks) and it corresponds to the maximum period of time
224 for which GCM will store and try to deliver the message. If this property is
225 not set, it is default to the maximum value. When a TTL is set to 0, GCM will
226 try to deliver the message immediately. If the immediate effort fails, the
227 message will be discarded.</li>
228 </ul>
229
230 <p>When the callback passed in $ref:gcm.send is called without runtime error, it does
231 not mean that the message was already delivered to the GCM server. Rather, it
232 means that it was queued for delivery. If the message fails to reach the
233 destination within the specified TTL period, for example due to network error,
234 the $ref:gcm.onSendError will be fired.</p>
235
236 <pre data-filename="background.js"><code>
237 // Substitute your own sender ID here. This is the project
238 // number you got from the Google Developers Console.
239 var senderId = "Your-Sender-ID";
240
241 // Make the message ID unique across the lifetime of your app.
242 // One way to achieve this is to use the auto-increment counter
243 // that is persisted to local storage.
244
245 // Message ID is saved to and restored from local storage.
246 var messageId = 0;
247 chrome.storage.local.get("messageId", function(result) {
248 if (chrome.runtime.lastError)
249 return;
250 messageId = parseInt(result["messageId"]);
251 if (isNaN(messageId))
252 messageId = 0;
253 });
254
255 // Sets up an event listener for send error.
256 chrome.gcm.onSendError.addListener(sendError);
257
258 // Returns a new ID to identify the message.
259 function getMessageId() {
260 messageId++;
261 chrome.storage.local.set({messageId: messageId});
262 return messageId.toString();
263 }
264
265 function sendMessage() {
266 var message = {
267 messageId: getMessageId(),
268 destinationId: senderId + "@gcm.googleapis.com",
269 timeToLive: 86400, // 1 day
270 data: {
271 "key1": "value1",
272 "key2": "value2"
273 }
274 };
275 chrome.gcm.send(message, function(messageId) {
276 if (chrome.runtime.lastError) {
277 // Some error occurred. Fail gracefully or try to send
278 // again.
279 return;
280 }
281
282 // The message has been accepted for delivery. If the message
283 // can not reach the destination, onSendError event will be
284 // fired.
285 });
286 }
287
288 function sendError(error) {
289 console.log("Message " + error.messageId +
290 " failed to be sent: " + error.errorMessage);
291 }
292 </code></pre>
293
294 <h3 id="messages_deleted_event">Messages deleted event</h3>
295
296 <p>GCM will store up to 100 non-collapsible messages. After that, all messages a re
297 discarded from GCM, and an event $ref:gcm.onMessagesDeleted will be fired, which
298 tells the client that it falls behind. Your app or extension should respond by
299 syncing with your application server to recover the discarded messages.</p>
300
301 <pre data-filename="background.js"><code>
302 chrome.gcm.onMessagesDeleted.addListener(messagesDeleted);
303
304 function messagesDeleted() {
305 // All messages have been discarded from GCM. Sync with
306 // your application server to recover from the situation.
307 }
308 </code></pre>
309
310 <h3 id="collapsible_messages">Collapsible messages</h3>
311
312 <p>GCM messages are often a tickle, telling the app or extension to contact the
313 server for fresh data. In GCM, it's possible to create collapsible messages for
314 this situation, wherein new messages replace older ones. When a collapse key is
315 provided and multiple messages are queued up in the GCM servers for the same
316 user, only the last one with any given collapse key is delivered to your app or
317 extension. As a result the <code>message</code> object passed to the $ref:gcm.on Message event
318 will contain a <code>collapseKey</code>field. For more details about sending col lapsible
319 messages, please refer to <a href="http://developer.android.com/google/gcm/adv.h tml#collapsible">GCM Advance
320 Topics</a>.</p>
321
322 <h2 id="publish_your_app">Publish your app</h2>
323
324 <p>To use the GCM service, you must publish your app in the <a href="https://dev elopers.google.com/chrome/web-store/docs/publish">Chrome Web
325 Store</a>.</p>
326
327 <h2 id="error_reference">Error reference</h2>
328
329 <p>An error could occur when a gcm API function is called. Your app or extension
330 should check $ref:runtime.lastError for more information in your callback. The
331 error code will also be passed as a parameter to $ref:gcm.onSendError event.</p>
332
333 <p>Here's a brief summary of the gcm errors:</p>
334
335 <ul>
336 <li><strong>Function was called with invalid parameters</strong>: this could hap pen when gcm
337 functions are called with bad parameters.</li>
338 <li><strong>Profile was not signed in</strong>: this could happen when gcm funct ions are called
339 from a profile that was not signed in.</li>
340 <li><strong>Asynchronous operation is pending</strong>: this could happen when c ertain gcm
341 function is called again without waiting for the callback passed in previous
342 function to be called.</li>
343 <li><strong>Network error occurred</strong>: this could happen when GCM server f ails to reach
344 due to network problem, like losing Internet connection.</li>
345 <li><strong>Server error occurred</strong>: this could happen when GCM server fa ils to reach
346 due to server problem, like server busy.</li>
347 <li><strong>Time-to-live exceeded</strong>: this could happen when a message cou ld not be
348 delivered within the specific time-to-live period.</li>
349 <li><strong>Unknown error occurred</strong>: this could happen due to any other internal
350 errors.</li>
351 </ul>
352
353 <h2 id="feedback">Feedback</h2>
354
355 <p>You can provide feedback about Google Cloud Messaging and the gcm API through
356 the Google Group <a href="https://groups.google.com/forum/#!forum/gcm-for-chrome -v2-feedback">GCM for Chrome V2
357 Feedback</a>.
358 Use this group to ask for help, file bug reports, and request features.</p>
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698