OLD | NEW |
| (Empty) |
1 <!DOCTYPE html><!-- This page is a placeholder for generated extensions api doc.
Note: | |
2 1) The <head> information in this page is significant, should be uniform | |
3 across api docs and should be edited only with knowledge of the | |
4 templating mechanism. | |
5 3) All <body>.innerHTML is genereated as an rendering step. If viewed in a | |
6 browser, it will be re-generated from the template, json schema and | |
7 authored overview content. | |
8 4) The <body>.innerHTML is also generated by an offline step so that this | |
9 page may easily be indexed by search engines. | |
10 --><html xmlns="http://www.w3.org/1999/xhtml"><head> | |
11 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> | |
12 <link href="css/ApiRefStyles.css" rel="stylesheet" type="text/css"> | |
13 <link href="css/print.css" rel="stylesheet" type="text/css" media="print"> | |
14 <script type="text/javascript" src="../../../third_party/jstemplate/jstempla
te_compiled.js"> | |
15 </script> | |
16 <script type="text/javascript" src="../../../../third_party/json_minify/mini
fy-sans-regexp.js"> | |
17 </script> | |
18 <script type="text/javascript" src="js/api_page_generator.js"></script> | |
19 <script type="text/javascript" src="js/bootstrap.js"></script> | |
20 <script type="text/javascript" src="js/sidebar.js"></script> | |
21 <title>Message Passing - Google Chrome Extensions - Google Code</title></head> | |
22 <body> <div id="devModeWarning" class="displayModeWarning"> | |
23 You are viewing extension docs in chrome via the 'file:' scheme: are you exp
ecting to see local changes when you refresh? You'll need run chrome with --allo
w-file-access-from-files. | |
24 </div> | |
25 <div id="branchWarning" class="displayModeWarning"> | |
26 <span>WARNING: This is the <span id="branchName">BETA</span> documentation. | |
27 It may not work with the stable release of Chrome.</span> | |
28 <select id="branchChooser"> | |
29 <option>Choose a different version... | |
30 </option><option value="">Stable | |
31 </option><option value="beta">Beta | |
32 </option><option value="dev">Dev | |
33 </option><option value="trunk">Trunk | |
34 </option></select> | |
35 </div> | |
36 <div id="unofficialWarning" class="displayModeWarning"> | |
37 <span>WARNING: This is unofficial documentation. It may not work with the | |
38 current release of Chrome.</span> | |
39 <button id="goToOfficialDocs">Go to the official docs</button> | |
40 </div> | |
41 <div id="gc-container" class="labs"> | |
42 <!-- SUBTEMPLATES: DO NOT MOVE FROM THIS LOCATION --> | |
43 <!-- In particular, sub-templates that recurse, must be used by allowing | |
44 jstemplate to make a copy of the template in this section which | |
45 are not operated on by way of the jsskip="true" --> | |
46 <!-- /SUBTEMPLATES --> | |
47 <a id="top"></a> | |
48 <div id="skipto"> | |
49 <a href="#gc-pagecontent">Skip to page content</a> | |
50 <a href="#gc-toc">Skip to main navigation</a> | |
51 </div> | |
52 <!-- API HEADER --> | |
53 <table id="header" width="100%" cellspacing="0" border="0"> | |
54 <tbody><tr> | |
55 <td valign="middle"><a href="http://code.google.com/"><img src="images/c
ode_labs_logo.gif" height="43" width="161" alt="Google Code Labs" style="border:
0; margin:0;"></a></td> | |
56 <td valign="middle" width="100%" style="padding-left:0.6em;"> | |
57 <form action="http://www.google.com/cse" id="cse" style="margin-top:0.
5em"> | |
58 <div id="gsc-search-box"> | |
59 <input type="hidden" name="cx" value="002967670403910741006:61_cvz
fqtno"> | |
60 <input type="hidden" name="ie" value="UTF-8"> | |
61 <input type="text" name="q" value="" size="55"> | |
62 <input class="gsc-search-button" type="submit" name="sa" value="Se
arch"> | |
63 <br> | |
64 <span class="greytext">e.g. "page action" or "tabs"</span> | |
65 </div> | |
66 </form> | |
67 <script type="text/javascript" src="https://www.google.com/jsapi"></sc
ript> | |
68 <script type="text/javascript">google.load("elements", "1", {packages:
"transliteration"});</script> | |
69 <script type="text/javascript" src="https://www.google.com/coop/cse/t1
3n?form=cse&t13n_langs=en"></script> | |
70 <script type="text/javascript" src="https://www.google.com/coop/cse/br
and?form=cse&lang=en"></script> | |
71 </td> | |
72 </tr> | |
73 </tbody></table> | |
74 <div id="codesiteContent" class=""> | |
75 <a id="gc-topnav-anchor"></a> | |
76 <div id="gc-topnav"> | |
77 <h1>Google Chrome Extensions (<a href="http://code.google.com/labs/">Lab
s</a>)</h1> | |
78 <ul id="home" class="gc-topnav-tabs"> | |
79 <li id="home_link"> | |
80 <a href="index.html" title="Google Chrome Extensions home page">Home
</a> | |
81 </li> | |
82 <li id="docs_link"> | |
83 <a href="docs.html" title="Official Google Chrome Extensions documen
tation">Docs</a> | |
84 </li> | |
85 <li id="faq_link"> | |
86 <a href="faq.html" title="Answers to frequently asked questions abou
t Google Chrome Extensions">FAQ</a> | |
87 </li> | |
88 <li id="samples_link"> | |
89 <a href="samples.html" title="Sample extensions (with source code)">
Samples</a> | |
90 </li> | |
91 <li id="group_link"> | |
92 <a href="http://groups.google.com/a/chromium.org/group/chromium-exte
nsions" title="Google Chrome Extensions developer forum">Group</a> | |
93 </li> | |
94 <li id="so_link"> | |
95 <a href="http://stackoverflow.com/questions/tagged/google-chrome-ext
ension" title="[google-chrome-extension] tag on Stack Overflow">Questions?</a> | |
96 </li> | |
97 </ul> | |
98 </div> <!-- end gc-topnav --> | |
99 <div class="g-section g-tpl-170"> | |
100 <!-- SIDENAV --> | |
101 <div class="g-unit g-first" id="gc-toc"> | |
102 <ul> | |
103 <li><a href="getstarted.html">Getting Started</a></li> | |
104 <li><a href="overview.html">Overview</a></li> | |
105 <li><a href="whats_new.html">What's New?</a></li> | |
106 <li><h2><a href="devguide.html">Developer's Guide</a></h2> | |
107 <ul> | |
108 <li>Browser UI | |
109 <ul> | |
110 <li><a href="browserAction.html">Browser Actions</a></li> | |
111 <li><a href="contextMenus.html">Context Menus</a></li> | |
112 <li><a href="notifications.html">Desktop Notifications</a></li
> | |
113 <li><a href="omnibox.html">Omnibox</a></li> | |
114 <li><a href="options.html">Options Pages</a></li> | |
115 <li><a href="override.html">Override Pages</a></li> | |
116 <li><a href="pageAction.html">Page Actions</a></li> | |
117 </ul> | |
118 </li> | |
119 <li>Browser Interaction | |
120 <ul> | |
121 <li><a href="bookmarks.html">Bookmarks</a></li> | |
122 <li><a href="cookies.html">Cookies</a></li> | |
123 <li><a href="devtools.html">Developer Tools</a></li> | |
124 <li><a href="events.html">Events</a></li> | |
125 <li><a href="history.html">History</a></li> | |
126 <li><a href="management.html">Management</a></li> | |
127 <li><a href="tabs.html">Tabs</a></li> | |
128 <li><a href="windows.html">Windows</a></li> | |
129 </ul> | |
130 </li> | |
131 <li>Implementation | |
132 <ul> | |
133 <li><a href="a11y.html">Accessibility</a></li> | |
134 <li><a href="background_pages.html">Background Pages</a></li> | |
135 <li><a href="content_scripts.html">Content Scripts</a></li> | |
136 <li><a href="xhr.html">Cross-Origin XHR</a></li> | |
137 <li><a href="i18n.html">Internationalization</a></li> | |
138 <li class="leftNavSelected">Message Passing</li> | |
139 <li><a href="permissions.html">Optional Permissions</a></li> | |
140 <li><a href="npapi.html">NPAPI Plugins</a></li> | |
141 </ul> | |
142 </li> | |
143 <li>Finishing | |
144 <ul> | |
145 <li><a href="hosting.html">Hosting</a></li> | |
146 <li><a href="external_extensions.html">Other Deployment Option
s</a></li> | |
147 </ul> | |
148 </li> | |
149 </ul> | |
150 </li> | |
151 <li><h2><a href="apps.html">Packaged Apps</a></h2></li> | |
152 <li><h2><a href="tutorials.html">Tutorials</a></h2> | |
153 <ul> | |
154 <li><a href="tut_debugging.html">Debugging</a></li> | |
155 <li><a href="tut_analytics.html">Google Analytics</a></li> | |
156 <li><a href="tut_oauth.html">OAuth</a></li> | |
157 </ul> | |
158 </li> | |
159 <li><h2>Reference</h2> | |
160 <ul> | |
161 <li>Formats | |
162 <ul> | |
163 <li><a href="manifest.html">Manifest Files</a></li> | |
164 <li><a href="match_patterns.html">Match Patterns</a></li> | |
165 </ul> | |
166 </li> | |
167 <li><a href="permission_warnings.html">Permission Warnings</a></li
> | |
168 <li><a href="api_index.html">chrome.* APIs</a></li> | |
169 <li><a href="api_other.html">Other APIs</a></li> | |
170 </ul> | |
171 </li> | |
172 <li><h2><a href="samples.html">Samples</a></h2></li> | |
173 <div class="line"> </div> | |
174 <li><h2>More</h2> | |
175 <ul> | |
176 <li><a href="http://code.google.com/chrome/webstore/docs/index.htm
l">Chrome Web Store</a></li> | |
177 <li><a href="http://code.google.com/chrome/apps/docs/developers_gu
ide.html">Hosted Apps</a></li> | |
178 <li><a href="themes.html">Themes</a></li> | |
179 </ul> | |
180 </li> | |
181 </ul> | |
182 </div> | |
183 <script> | |
184 initToggles(); | |
185 </script> | |
186 <div class="g-unit" id="gc-pagecontent"> | |
187 <div id="pageTitle"> | |
188 <h1 class="page_title">Message Passing</h1> | |
189 </div> | |
190 <!-- TABLE OF CONTENTS --> | |
191 <div id="toc"> | |
192 <h2>Contents</h2> | |
193 <ol> | |
194 <li> | |
195 <a href="#simple">Simple one-time requests</a> | |
196 <ol> | |
197 </ol> | |
198 </li><li> | |
199 <a href="#connect">Long-lived connections</a> | |
200 <ol> | |
201 </ol> | |
202 </li><li> | |
203 <a href="#external">Cross-extension messaging</a> | |
204 <ol> | |
205 </ol> | |
206 </li><li> | |
207 <a href="#security-considerations">Security considerations</a> | |
208 <ol> | |
209 </ol> | |
210 </li><li> | |
211 <a href="#examples">Examples</a> | |
212 <ol> | |
213 </ol> | |
214 </li> | |
215 </ol> | |
216 </div> | |
217 <!-- /TABLE OF CONTENTS --> | |
218 <!-- Standard content lead-in for experimental API pages --> | |
219 <!-- STATIC CONTENT PLACEHOLDER --> | |
220 <div id="static"><div id="pageData-name" class="pageData">Message Passin
g</div> | |
221 <div id="pageData-showTOC" class="pageData">true</div> | |
222 <p> | |
223 Since content scripts run in the context of a web page and not the extension, | |
224 they often need some way of communicating with the rest of the extension. For | |
225 example, an RSS reader extension might use content scripts to detect the | |
226 presence of an RSS feed on a page, then notify the background page in order to | |
227 display a page action icon for that page. | |
228 </p><p> | |
229 Communication between extensions and their content scripts works by using | |
230 message passing. Either side can listen for messages sent from the other end, | |
231 and respond on the same channel. A message can contain any valid JSON object | |
232 (null, boolean, number, string, array, or object). There is a simple API for | |
233 <a href="#simple">one-time requests</a> | |
234 and a more complex API that allows you to have | |
235 <a href="#connect">long-lived connections</a> | |
236 for exchanging multiple messages with a shared context. It is also possible to | |
237 send a message to another extension if you know its ID, which is covered in | |
238 the | |
239 <a href="#external">cross-extension messages</a> | |
240 section. | |
241 </p><h2 id="simple">Simple one-time requests</h2> | |
242 <p> | |
243 If you only need to send a single message to another part of your extension | |
244 (and optionally get a response back), you should use the simplified | |
245 <a href="extension.html#method-sendMessage">chrome.extension.sendMessage()</a> | |
246 or | |
247 <a href="tabs.html#method-sendMessage">chrome.tabs.sendMessage()</a> | |
248 methods. This lets you send a one-time JSON-serializable message from a | |
249 content script to extension, or vice versa, respectively. An optional | |
250 callback parameter allows you handle the response from the other side, if | |
251 there is one. | |
252 </p><p> | |
253 Sending a request from a content script looks like this: | |
254 </p><pre>contentscript.js | |
255 ================ | |
256 chrome.extension.sendMessage({greeting: "hello"}, function(response) { | |
257 console.log(response.farewell); | |
258 }); | |
259 </pre> | |
260 <p> | |
261 Sending a request from the extension to a content script looks very similar, | |
262 except that you need to specify which tab to send it to. This example | |
263 demonstrates sending a message to the content script in the selected tab. | |
264 </p><pre>background.html | |
265 =============== | |
266 chrome.tabs.getSelected(null, function(tab) { | |
267 chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(response) { | |
268 console.log(response.farewell); | |
269 }); | |
270 }); | |
271 </pre> | |
272 <p> | |
273 On the receiving end, you need to set up an | |
274 <a href="extension.html#event-onMessage">chrome.extension.onMessage</a> | |
275 event listener to handle the message. This looks the same from a content | |
276 script or extension page. | |
277 </p><pre>chrome.extension.onMessage.addListener( | |
278 function(request, sender, sendResponse) { | |
279 console.log(sender.tab ? | |
280 "from a content script:" + sender.tab.url : | |
281 "from the extension"); | |
282 if (request.greeting == "hello") | |
283 sendResponse({farewell: "goodbye"}); | |
284 }); | |
285 </pre> | |
286 <p class="note"> | |
287 <b>Note:</b> If multiple pages are listening for onMessage events, only the | |
288 first to call sendResponse() for a particular event will succeed in sending the | |
289 response. All other responses to that event will be ignored. | |
290 </p> | |
291 <h2 id="connect">Long-lived connections</h2> | |
292 <p> | |
293 Sometimes it's useful to have a conversation that lasts longer than a single | |
294 request and response. In this case, you can open a long-lived channel from | |
295 your content script to an extension page, or vice versa, using | |
296 <a href="extension.html#method-connect">chrome.extension.connect()</a> | |
297 or | |
298 <a href="tabs.html#method-connect">chrome.tabs.connect()</a> respectively. The | |
299 channel can optionally have a name, allowing you to distinguish between | |
300 different types of connections. | |
301 </p><p> | |
302 One use case might be an automatic form fill extension. The content script | |
303 could open a channel to the extension page for a particular login, and send a | |
304 message to the extension for each input element on the page to request the | |
305 form data to fill in. The shared connection allows the extension to keep | |
306 shared state linking the several messages coming from the content script. | |
307 </p><p> | |
308 When establishing a connection, each end is given a | |
309 <a href="extension.html#type-Port">Port</a> | |
310 object which is used for sending and receiving messages through that | |
311 connection. | |
312 </p><p> | |
313 Here is how you open a channel from a content script, and send and listen for | |
314 messages: | |
315 </p><pre>contentscript.js | |
316 ================ | |
317 var port = chrome.extension.connect({name: "knockknock"}); | |
318 port.postMessage({joke: "Knock knock"}); | |
319 port.onMessage.addListener(function(msg) { | |
320 if (msg.question == "Who's there?") | |
321 port.postMessage({answer: "Madame"}); | |
322 else if (msg.question == "Madame who?") | |
323 port.postMessage({answer: "Madame... Bovary"}); | |
324 }); | |
325 </pre> | |
326 <p> | |
327 Sending a request from the extension to a content script looks very similar, | |
328 except that you need to specify which tab to connect to. Simply replace the | |
329 call to connect in the above example with | |
330 <a href="tabs.html#method-connect">chrome.tabs.connect(tabId, {name: | |
331 "knockknock"})</a>. | |
332 </p><p> | |
333 In order to handle incoming connections, you need to set up a | |
334 <a href="extension.html#event-onConnect">chrome.extension.onConnect</a> | |
335 event listener. This looks the same from a content script or an extension | |
336 page. When another part of your extension calls "connect()", this event is | |
337 fired, along with the | |
338 <a href="extension.html#type-Port">Port</a> | |
339 object you can use to send and receive messages through the connection. Here's | |
340 what it looks like to respond to incoming connections: | |
341 </p><pre>chrome.extension.onConnect.addListener(function(port) { | |
342 console.assert(port.name == "knockknock"); | |
343 port.onMessage.addListener(function(msg) { | |
344 if (msg.joke == "Knock knock") | |
345 port.postMessage({question: "Who's there?"}); | |
346 else if (msg.answer == "Madame") | |
347 port.postMessage({question: "Madame who?"}); | |
348 else if (msg.answer == "Madame... Bovary") | |
349 port.postMessage({question: "I don't get it."}); | |
350 }); | |
351 }); | |
352 </pre> | |
353 <p> | |
354 You may want to find out when a connection is closed, for example if you are | |
355 maintaining separate state for each open port. For this you can listen to the | |
356 <a href="extension.html#type-Port">Port.onDisconnect</a> | |
357 event. This event is fired either when the other side of the channel manually | |
358 calls | |
359 <a href="extension.html#type-Port">Port.disconnect()</a>, or when the page | |
360 containing the port is unloaded (for example if the tab is navigated). | |
361 onDisconnect is guaranteed to be fired only once for any given port. | |
362 </p><h2 id="external">Cross-extension messaging</h2> | |
363 <p> | |
364 In addition to sending messages between different components in your | |
365 extension, you can use the messaging API to communicate with other extensions. | |
366 This lets you expose a public API that other extensions can take advantage of. | |
367 </p><p> | |
368 Listening for incoming requests and connections is similar to the internal | |
369 case, except you use the | |
370 <a href="extension.html#event-onMessageExternal">chrome.extension.onMessageExter
nal</a> | |
371 or | |
372 <a href="extension.html#event-onConnectExternal">chrome.extension.onConnectExter
nal</a> | |
373 methods. Here's an example of each: | |
374 </p><pre>// For simple requests: | |
375 chrome.extension.onMessageExternal.addListener( | |
376 function(request, sender, sendResponse) { | |
377 if (sender.id == blacklistedExtension) | |
378 return; // don't allow this extension access | |
379 else if (request.getTargetData) | |
380 sendResponse({targetData: targetData}); | |
381 else if (request.activateLasers) { | |
382 var success = activateLasers(); | |
383 sendResponse({activateLasers: success}); | |
384 } | |
385 }); | |
386 // For long-lived connections: | |
387 chrome.extension.onConnectExternal.addListener(function(port) { | |
388 port.onMessage.addListener(function(msg) { | |
389 // See other examples for sample onMessage handlers. | |
390 }); | |
391 }); | |
392 </pre> | |
393 <p> | |
394 Likewise, sending a message to another extension is similar to sending one | |
395 within your extension. The only difference is that you must pass the ID of the | |
396 extension you want to communicate with. For example: | |
397 </p><pre>// The ID of the extension we want to talk to. | |
398 var laserExtensionId = "abcdefghijklmnoabcdefhijklmnoabc"; | |
399 // Make a simple request: | |
400 chrome.extension.sendMessage(laserExtensionId, {getTargetData: true}, | |
401 function(response) { | |
402 if (targetInRange(response.targetData)) | |
403 chrome.extension.sendMessage(laserExtensionId, {activateLasers: true}); | |
404 }); | |
405 // Start a long-running conversation: | |
406 var port = chrome.extension.connect(laserExtensionId); | |
407 port.postMessage(...); | |
408 </pre> | |
409 <h2 id="security-considerations">Security considerations</h2> | |
410 <p> | |
411 When receiving a message from a content script or another extension, your | |
412 background page should be careful not to fall victim to <a href="http://en.wikip
edia.org/wiki/Cross-site_scripting">cross-site | |
413 scripting</a>. Specifically, avoid using dangerous APIs such as the | |
414 below: | |
415 </p> | |
416 <pre>background.html | |
417 =============== | |
418 chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(response) { | |
419 // WARNING! Might be evaluating an evil script! | |
420 var resp = eval("(" + response.farewell + ")"); | |
421 }); | |
422 background.html | |
423 =============== | |
424 chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(response) { | |
425 // WARNING! Might be injecting a malicious script! | |
426 document.getElementById("resp").innerHTML = response.farewell; | |
427 }); | |
428 </pre> | |
429 <p> | |
430 Instead, prefer safer APIs that do not run scripts: | |
431 </p> | |
432 <pre>background.html | |
433 =============== | |
434 chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(response) { | |
435 // JSON.parse does not evaluate the attacker's scripts. | |
436 var resp = JSON.parse(response.farewell); | |
437 }); | |
438 background.html | |
439 =============== | |
440 chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(response) { | |
441 // innerText does not let the attacker inject HTML elements. | |
442 document.getElementById("resp").innerText = response.farewell; | |
443 }); | |
444 </pre> | |
445 <h2 id="examples">Examples</h2> | |
446 <p> | |
447 You can find simple examples of communication via messages in the | |
448 <a href="http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extension
s/docs/examples/api/messaging/">examples/api/messaging</a> | |
449 directory. | |
450 Also see the | |
451 <a href="http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extension
s/docs/examples/howto/contentscript_xhr">contentscript_xhr</a> example, | |
452 in which a content script and its parent extension exchange messages, | |
453 so that the parent extension can perform | |
454 cross-site requests on behalf of the content script. | |
455 For more examples and for help in viewing the source code, see | |
456 <a href="samples.html">Samples</a>. | |
457 </p> | |
458 </div> | |
459 <!-- API PAGE --> | |
460 <!-- /apiPage --> | |
461 </div> <!-- /gc-pagecontent --> | |
462 </div> <!-- /g-section --> | |
463 </div> <!-- /codesiteContent --> | |
464 <div id="gc-footer" --=""> | |
465 <div class="text"> | |
466 <p> | |
467 Except as otherwise <a href="http://code.google.com/policies.html#restrictions
">noted</a>, | |
468 the content of this page is licensed under the <a rel="license" href="http://c
reativecommons.org/licenses/by/3.0/">Creative Commons | |
469 Attribution 3.0 License</a>, and code samples are licensed under the | |
470 <a rel="license" href="http://code.google.com/google_bsd_license.html">BSD Lic
ense</a>. | |
471 </p> | |
472 <p> | |
473 ©2011 Google | |
474 </p> | |
475 <!-- begin analytics --> | |
476 <script src="https://www.google-analytics.com/urchin.js" type="text/javascript">
</script> | |
477 <script src="https://www.google-analytics.com/ga.js" type="text/javascript"></sc
ript> | |
478 <script type="text/javascript"> | |
479 // chrome doc tracking | |
480 try { | |
481 var engdocs = _gat._getTracker("YT-10763712-2"); | |
482 engdocs._trackPageview(); | |
483 } catch(err) {} | |
484 // code.google.com site-wide tracking | |
485 try { | |
486 _uacct="UA-18071-1"; | |
487 _uanchor=1; | |
488 _uff=0; | |
489 urchinTracker(); | |
490 } | |
491 catch(e) {/* urchinTracker not available. */} | |
492 </script> | |
493 <!-- end analytics --> | |
494 </div> | |
495 </div> <!-- /gc-footer --> | |
496 </div> <!-- /gc-container --> | |
497 </body></html> | |
OLD | NEW |