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>Content Scripts - 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 class="leftNavSelected">Content Scripts</li> | |
136 <li><a href="xhr.html">Cross-Origin XHR</a></li> | |
137 <li><a href="i18n.html">Internationalization</a></li> | |
138 <li><a href="messaging.html">Message Passing</a></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">Content Scripts</h1> | |
189 </div> | |
190 <!-- TABLE OF CONTENTS --> | |
191 <div id="toc"> | |
192 <h2>Contents</h2> | |
193 <ol> | |
194 <li> | |
195 <a href="#registration">Manifest</a> | |
196 <ol> | |
197 <li> | |
198 <a href="#match-patterns-globs">Match patterns and globs</a> | |
199 </li> | |
200 </ol> | |
201 </li><li> | |
202 <a href="#pi">Programmatic injection</a> | |
203 <ol> | |
204 </ol> | |
205 </li><li> | |
206 <a href="#execution-environment">Execution environment</a> | |
207 <ol> | |
208 </ol> | |
209 </li><li> | |
210 <a href="#host-page-communication">Communication with the embeddin
g page</a> | |
211 <ol> | |
212 </ol> | |
213 </li><li> | |
214 <a href="#security-considerations">Security considerations</a> | |
215 <ol> | |
216 </ol> | |
217 </li><li> | |
218 <a href="#extension-files">Referring to extension files</a> | |
219 <ol> | |
220 </ol> | |
221 </li><li> | |
222 <a href="#examples"> Examples </a> | |
223 <ol> | |
224 </ol> | |
225 </li><li> | |
226 <a href="#videos"> Videos </a> | |
227 <ol> | |
228 </ol> | |
229 </li> | |
230 </ol> | |
231 </div> | |
232 <!-- /TABLE OF CONTENTS --> | |
233 <!-- Standard content lead-in for experimental API pages --> | |
234 <!-- STATIC CONTENT PLACEHOLDER --> | |
235 <div id="static"><div id="pageData-name" class="pageData">Content Script
s</div> | |
236 <div id="pageData-showTOC" class="pageData">true</div> | |
237 <p> | |
238 Content scripts are JavaScript files that run in the context of web pages. | |
239 By using the standard | |
240 <a href="http://www.w3.org/TR/DOM-Level-2-HTML/">Document | |
241 Object Model</a> (DOM), | |
242 they can read details of the web pages the browser visits, | |
243 or make changes to them. | |
244 </p> | |
245 <p> | |
246 Here are some examples of what content scripts can do: | |
247 </p> | |
248 <ul> | |
249 <li>Find unlinked URLs in web pages and convert them into hyperlinks | |
250 </li><li>Increase the font size to make text more legible | |
251 </li><li>Find and process <a href="http://microformats.org/">microformat</a> d
ata in the DOM | |
252 </li></ul> | |
253 <p> | |
254 However, content scripts have some limitations. | |
255 They <b>cannot</b>: | |
256 </p> | |
257 <ul> | |
258 <li> | |
259 Use chrome.* APIs | |
260 (except for parts of | |
261 <a href="extension.html"><code>chrome.extension</code></a>) | |
262 </li> | |
263 <li> | |
264 Use variables or functions defined by their extension's pages | |
265 </li> | |
266 <li> | |
267 Use variables or functions defined by web pages or by other content scripts | |
268 </li> | |
269 </ul> | |
270 <p> | |
271 These limitations aren't as bad as they sound. | |
272 Content scripts can <em>indirectly</em> use the chrome.* APIs, | |
273 get access to extension data, | |
274 and request extension actions | |
275 by exchanging <a href="messaging.html">messages</a> | |
276 with their parent extension. | |
277 Content scripts can also | |
278 make <a href="xhr.html">cross-site XMLHttpRequests</a> | |
279 to the same sites as their parent extensions, | |
280 and they can | |
281 <a href="#host-page-communication">communicate with web pages</a> | |
282 using the shared DOM. | |
283 For more insight into what content scripts can and can't do, | |
284 learn about the | |
285 <a href="#execution-environment">execution environment</a>. | |
286 </p> | |
287 <h2 id="registration">Manifest</h2> | |
288 <p>If your content script's code should always be injected, | |
289 register it in the | |
290 <a href="manifest.html">extension manifest</a> | |
291 using the <code>content_scripts</code> field, | |
292 as in the following example. | |
293 </p> | |
294 <pre>{ | |
295 "name": "My extension", | |
296 ... | |
297 <b>"content_scripts": [ | |
298 { | |
299 "matches": ["http://www.google.com/*"], | |
300 "css": ["mystyles.css"], | |
301 "js": ["jquery.js", "myscript.js"] | |
302 } | |
303 ]</b>, | |
304 ... | |
305 }</pre> | |
306 <p> | |
307 If you want to inject the code only sometimes, | |
308 use the | |
309 <a href="manifest.html#permissions"><code>permissions</code></a> field instead, | |
310 as described in <a href="#pi">Programmatic injection</a>. | |
311 </p> | |
312 <pre>{ | |
313 "name": "My extension", | |
314 ... | |
315 <b>"permissions": [ | |
316 "tabs", "http://www.google.com/*" | |
317 ]</b>, | |
318 ... | |
319 }</pre> | |
320 <p> | |
321 Using the <code>content_scripts</code> field, | |
322 an extension can insert multiple content scripts into a page; | |
323 each of these content scripts can have multiple JavaScript and CSS files. | |
324 Each item in the <code>content_scripts</code> array | |
325 can have the following properties:</p> | |
326 <table> | |
327 <tbody><tr> | |
328 <th>Name</th> | |
329 <th>Type</th> | |
330 <th>Description</th> | |
331 </tr> | |
332 <tr> | |
333 <td><code>matches</code></td> | |
334 <td>array of strings</td> | |
335 <td><em>Required.</em> | |
336 Specifies which pages this content script will be injected into. | |
337 See <a href="match_patterns.html">Match Patterns</a> | |
338 for more details on the syntax of these strings | |
339 and <a href="#match-patterns-globs">Match patterns and globs</a> | |
340 for information on how to exclude URLs.</td> | |
341 </tr> | |
342 <tr> | |
343 <td><code>exclude_matches</code></td> | |
344 <td>array of strings</td> | |
345 <td><em>Optional.</em> | |
346 Excludes pages that this content script would otherwise be | |
347 injected into. | |
348 See <a href="match_patterns.html">Match Patterns</a> | |
349 for more details on the syntax of these strings | |
350 and <a href="#match-patterns-globs">Match patterns and globs</a> | |
351 for information on how to exclude URLs.</td> | |
352 </tr> | |
353 <tr> | |
354 <td><code>css<code></code></code></td> | |
355 <td>array of strings</td> | |
356 <td><em>Optional.</em> | |
357 The list of CSS files to be injected into matching pages. These are injected
in the order they appear in this array, before any DOM is constructed or displa
yed for the page.</td> | |
358 </tr> | |
359 <tr> | |
360 <td><code>js<code></code></code></td> | |
361 <td><nobr>array of strings</nobr></td> | |
362 <td><em>Optional.</em> | |
363 The list of JavaScript files to be injected into matching pages. These are i
njected in the order they appear in this array.</td> | |
364 </tr> | |
365 <tr id="run_at"> | |
366 <td><code>run_at<code></code></code></td> | |
367 <td>string</td> | |
368 <td><em>Optional.</em> | |
369 Controls when the files in <code>js</code> are injected. Can be "document_st
art", "document_end", or "document_idle". Defaults to "document_idle". | |
370 <br><br> | |
371 In the case of "document_start", the files are injected after any files from
<code>css</code>, but before any other DOM is constructed or any other script i
s run. | |
372 <br><br> | |
373 In the case of "document_end", the files are injected immediately after the
DOM is complete, but before subresources like images and frames have loaded. | |
374 <br><br> | |
375 In the case of "document_idle", the browser chooses a time to inject scripts
between "document_end" and immediately after the <code><a href="http://www.what
wg.org/specs/web-apps/current-work/#handler-onload">window.onload</a></code> eve
nt fires. The exact moment of injection depends on how complex the document is a
nd how long it is taking to load, and is optimized for page load speed. | |
376 <br><br> | |
377 <b>Note:</b> With "document_idle", content scripts may not necessarily recei
ve the <code>window.onload</code> event, because they may run after it has | |
378 already fired. In most cases, listening for the <code>onload</code> event is
unnecessary for content scripts running at "document_idle" because they are gua
ranteed to run after the DOM is complete. If your script definitely needs to run
after <code>window.onload</code>, you can check if <code>onload</code> has alre
ady fired by using the <code><a href="http://www.whatwg.org/specs/web-apps/curre
nt-work/#dom-document-readystate">document.readyState</a></code> property.</td> | |
379 </tr> | |
380 <tr> | |
381 <td><code>all_frames<code></code></code></td> | |
382 <td>boolean</td> | |
383 <td><em>Optional.</em> | |
384 Controls whether the content script runs in all frames of the matching page,
or only the top frame. | |
385 <br><br> | |
386 Defaults to <code>false</code>, meaning that only the top frame is matched.<
/td> | |
387 </tr> | |
388 <tr> | |
389 <td><code>include_globs</code></td> | |
390 <td>array of string</td> | |
391 <td><em>Optional.</em> | |
392 Applied after <code>matches</code> to include only those URLs that also matc
h this glob. Intended to emulate the <a href="http://wiki.greasespot.net/Metadat
a_Block#.40include"><code>@include</code></a> Greasemonkey keyword. | |
393 See <a href="#match-patterns-globs">Match patterns and globs</a> below for m
ore details.</td> | |
394 </tr> | |
395 <tr> | |
396 <td><code>exclude_globs</code></td> | |
397 <td>array of string</td> | |
398 <td><em>Optional.</em> | |
399 Applied after <code>matches</code> to exclude URLs that match this glob. | |
400 Intended to emulate the <a href="http://wiki.greasespot.net/Metadata_Block#.
40include"><code>@exclude</code></a> Greasemonkey keyword. | |
401 See <a href="#match-patterns-globs">Match patterns and globs</a> below for m
ore details.</td> | |
402 </tr> | |
403 </tbody></table> | |
404 <h3 id="match-patterns-globs">Match patterns and globs</h3> | |
405 <p> | |
406 The content script will be injected into a page if its URL matches any <code>mat
ches</code> pattern and any <code>include_globs</code> pattern, as long as the U
RL doesn't also match an <code>exclude_matches</code> or <code>exclude_globs</co
de> pattern. | |
407 Because the <code>matches</code> property is required, <code>exclude_matches</co
de>, <code>include_globs</code>, and <code>exclude_globs</code> can only be used
to limit which pages will be affected. | |
408 </p> | |
409 <p> | |
410 For example, assume <code>matches</code> is <code>["http://*.nytimes.com/*"]</co
de>: | |
411 </p> | |
412 <ul> | |
413 <li>If <code>exclude_matches</code> is <code>["*://*/*business*"]</code>, then t
he content script would be injected into "http://www.nytimes.com/health" but not
into "http://www.nytimes.com/business".</li> | |
414 <li>If <code>include_globs</code> is <code>["*nytimes.com/???s/*"]</code>, then
the content script would be injected into "http:/www.nytimes.com/arts/index.html
" and "http://www.nytimes.com/jobs/index.html" but not into "http://www.nytimes.
com/sports/index.html".</li> | |
415 <li>If <code>exclude_globs</code> is <code>["*science*"]</code>, then the conten
t script would be injected into "http://www.nytimes.com" but not into "http://sc
ience.nytimes.com" or "http://www.nytimes.com/science".</li> | |
416 </ul> | |
417 <p> | |
418 </p><p> | |
419 Glob properties follow a different, more flexible syntax than <a href="match_pat
terns.html">match patterns</a>. Acceptable glob strings are URLs that may conta
in "wildcard" asterisks and question marks. The asterisk (*) matches any string
of any length (including the empty string); the question mark (?) matches any si
ngle character. | |
420 </p> | |
421 <p> | |
422 For example, the glob "http://???.example.com/foo/*" matches any of the followin
g: | |
423 </p> | |
424 <ul> | |
425 <li>"http://www.example.com/foo/bar"</li> | |
426 <li>"http://the.example.com/foo/"</li> | |
427 </ul> | |
428 <p> | |
429 However, it does <em>not</em> match the following: | |
430 </p> | |
431 <ul> | |
432 <li>"http://my.example.com/foo/bar"</li> | |
433 <li>"http://example.com/foo/"</li> | |
434 <li>"http://www.example.com/foo"</li> | |
435 </ul> | |
436 <h2 id="pi">Programmatic injection</h2> | |
437 <p> | |
438 Inserting code into a page programmatically is useful | |
439 when your JavaScript or CSS code | |
440 shouldn't be injected into every single page | |
441 that matches the pattern — | |
442 for example, if you want a script to run | |
443 only when the user clicks a browser action's icon. | |
444 </p> | |
445 <p> | |
446 To insert code into a page, | |
447 your extension must have | |
448 <a href="xhr.html#requesting-permission">cross-origin permissions</a> | |
449 for the page. | |
450 It also must be able to use the <code>chrome.tabs</code> module. | |
451 You can get both kinds of permission | |
452 using the manifest file's | |
453 <a href="manifest.html#permissions">permissions</a> field. | |
454 </p> | |
455 <p> | |
456 Once you have permissions set up, | |
457 you can inject JavaScript into a page by calling | |
458 <a href="tabs.html#method-executeScript"><code>executeScript()</code></a>. | |
459 To inject CSS, use | |
460 <a href="tabs.html#method-insertCSS"><code>insertCSS()</code></a>. | |
461 </p> | |
462 <p> | |
463 The following code | |
464 (from the | |
465 <a href="http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extension
s/docs/examples/api/browserAction/make_page_red/">make_page_red</a> example) | |
466 reacts to a user click | |
467 by inserting JavaScript into the current tab's page | |
468 and executing the script. | |
469 </p> | |
470 <pre><em>/* in background.html */</em> | |
471 chrome.browserAction.onClicked.addListener(function(tab) { | |
472 chrome.tabs.executeScript(null, | |
473 {code:"document.body.bgColor='red'"}); | |
474 }); | |
475 <em>/* in manifest.json */</em> | |
476 "permissions": [ | |
477 "tabs", "http://*/*" | |
478 ], | |
479 </pre> | |
480 <p> | |
481 When the browser is displaying an HTTP page | |
482 and the user clicks this extension's browser action, | |
483 the extension sets the page's <code>bgcolor</code> property to 'red'. | |
484 The result, | |
485 unless the page has CSS that sets the background color, | |
486 is that the page turns red. | |
487 </p> | |
488 <p> | |
489 Usually, instead of inserting code directly (as in the previous sample), | |
490 you put the code in a file. | |
491 You inject the file's contents like this: | |
492 </p> | |
493 <pre>chrome.tabs.executeScript(null, {file: "content_script.js"});</pre> | |
494 <h2 id="execution-environment">Execution environment</h2> | |
495 <p>Content scripts execute in a special environment called an <em>isolated world
</em>. They have access to the DOM of the page they are injected into, but not t
o any JavaScript variables or functions created by the page. It looks to each co
ntent script as if there is no other JavaScript executing on the page it is runn
ing on. The same is true in reverse: JavaScript running on the page cannot call
any functions or access any variables defined by content scripts. | |
496 </p><p>For example, consider this simple page: | |
497 </p><pre>hello.html | |
498 ========== | |
499 <html> | |
500 <button id="mybutton">click me</button> | |
501 <script> | |
502 var greeting = "hello, "; | |
503 var button = document.getElementById("mybutton"); | |
504 button.person_name = "Bob"; | |
505 button.addEventListener("click", function() { | |
506 alert(greeting + button.person_name + "."); | |
507 }, false); | |
508 </script> | |
509 </html></pre> | |
510 <p>Now, suppose this content script was injected into hello.html: | |
511 </p><pre>contentscript.js | |
512 ================ | |
513 var greeting = "hola, "; | |
514 var button = document.getElementById("mybutton"); | |
515 button.person_name = "Roberto"; | |
516 button.addEventListener("click", function() { | |
517 alert(greeting + button.person_name + "."); | |
518 }, false); | |
519 </pre> | |
520 <p>Now, if the button is pressed, you will see both greetings. | |
521 </p><p>Isolated worlds allow each content script to make changes to its JavaScri
pt environment without worrying about conflicting with the page or with other co
ntent scripts. For example, a content script could include JQuery v1 and the pag
e could include JQuery v2, and they wouldn't conflict with each other. | |
522 </p><p>Another important benefit of isolated worlds is that they completely sepa
rate the JavaScript on the page from the JavaScript in extensions. This allows u
s to offer extra functionality to content scripts that should not be accessible
from web pages without worrying about web pages accessing it. | |
523 </p><h2 id="host-page-communication">Communication with the embedding page</h2> | |
524 <p>Although the execution environments of content scripts and the pages that hos
t them are isolated from each other, they share access to the page's DOM. If the
page wishes to communicate with the content script (or with the extension via t
he content script), it must do so through the shared DOM.</p> | |
525 <p>An example can be accomplished using window.postMessage (or window.webkitPost
Message for Transferable objects):</p> | |
526 <pre>contentscript.js | |
527 ================ | |
528 var port = chrome.extension.connect(); | |
529 window.addEventListener("message", function(event) { | |
530 // We only accept messages from ourselves | |
531 if (event.source != window) | |
532 return; | |
533 if (event.data.type && (event.data.type == "FROM_PAGE")) { | |
534 console.log("Content script received: " + event.data.text); | |
535 port.postMessage(event.data.text); | |
536 } | |
537 }, false);</pre> | |
538 <pre>http://foo.com/example.html | |
539 =========================== | |
540 document.getElementById("theButton").addEventListener("click", function() { | |
541 window.postMessage({ type: "FROM_PAGE", text: "Hello from the webpage!" }, "
*"); | |
542 }, false);</pre> | |
543 <p>In the above example, example.html (which is not a part of the extension) pos
ts messages to itself, which are intercepted and inspected by the content script
, and then posted to the extension process. In this way, the page establishes a
line of communication to the extension process. The reverse is possible through
similar means.</p> | |
544 <h2 id="security-considerations">Security considerations</h2> | |
545 <p>When writing a content script, you should be aware of two security issues. | |
546 First, be careful not to introduce security vulnerabilities into the web site | |
547 your content script is injected into. For example, if your content script | |
548 receives content from another web site (for example, by making an <a href="messa
ging.html">XMLHttpRequest</a>), | |
549 be careful to filter that content for <a href="http://en.wikipedia.org/wiki/Cros
s-site_scripting">cross-site | |
550 scripting</a> attacks before injecting the content into the current page. | |
551 For example, prefer to inject content via innerText rather than innerHTML. | |
552 Be especially careful when retrieving HTTP content on an HTTPS page because | |
553 the HTTP content might have been corrupted by a network <a href="http://en.wikip
edia.org/wiki/Man-in-the-middle_attack">"man-in-the-middle"</a> | |
554 if the user is on a hostile network.</p> | |
555 <p>Second, although running your content script in an isolated world provides | |
556 some protection from the web page, a malicious web page might still be able | |
557 to attack your content script if you use content from the web page | |
558 indiscriminately. For example, the following patterns are dangerous: | |
559 </p><pre>contentscript.js | |
560 ================ | |
561 var data = document.getElementById("json-data") | |
562 // WARNING! Might be evaluating an evil script! | |
563 var parsed = eval("(" + data + ")") | |
564 contentscript.js | |
565 ================ | |
566 var elmt_id = ... | |
567 // WARNING! elmt_id might be "); ... evil script ... //"! | |
568 window.setTimeout("animate(" + elmt_id + ")", 200); | |
569 </pre> | |
570 <p>Instead, prefer safer APIs that do not run scripts:</p> | |
571 <pre>contentscript.js | |
572 ================ | |
573 var data = document.getElementById("json-data") | |
574 // JSON.parse does not evaluate the attacker's scripts. | |
575 var parsed = JSON.parse(data) | |
576 contentscript.js | |
577 ================ | |
578 var elmt_id = ... | |
579 // The closure form of setTimeout does not evaluate scripts. | |
580 window.setTimeout(function() { | |
581 animate(elmt_id); | |
582 }, 200); | |
583 </pre> | |
584 <h2 id="extension-files">Referring to extension files</h2> | |
585 <p> | |
586 Get the URL of an extension's file using | |
587 <code>chrome.extension.getURL()</code>. | |
588 You can use the result | |
589 just like you would any other URL, | |
590 as the following code shows. | |
591 </p> | |
592 <pre><em>//Code for displaying <extensionDir>/images/myimage.png:</em> | |
593 var imgURL = <b>chrome.extension.getURL("images/myimage.png")</b>; | |
594 document.getElementById("someImage").src = imgURL; | |
595 </pre> | |
596 <h2 id="examples"> Examples </h2> | |
597 <p> | |
598 You can find many | |
599 <a href="samples.html#script">examples that use content scripts</a>. | |
600 A simple example of communication via messages is in the | |
601 <a href="samples.html#51a83d2ba3a32e3ff1bdb624d4e18ccec4c4038e">timer sample</a>
. | |
602 See <a href="samples.html#ede3c47b7757245be42ec33fd5ca63df4b490066">make_page_re
d</a> and | |
603 <a href="samples.html#028eb5364924344029bcbe1d527f132fc72b34e5">email_this_page<
/a> | |
604 for examples of programmatic injection. | |
605 </p> | |
606 <h2 id="videos"> Videos </h2> | |
607 <p> | |
608 The following videos discuss concepts that are important for content scripts. | |
609 The first video describes content scripts and isolated worlds. | |
610 </p> | |
611 <p> | |
612 <iframe title="YouTube video player" width="640" height="390" src="http://www.yo
utube.com/embed/laLudeUmXHM?rel=0" frameborder="0" allowfullscreen=""></iframe> | |
613 </p> | |
614 <p> | |
615 The next video describes message passing, | |
616 featuring an example of a content script | |
617 sending a request to its parent extension. | |
618 </p> | |
619 <p> | |
620 <iframe title="YouTube video player" width="640" height="390" src="http://www.yo
utube.com/embed/B4M_a7xejYI?rel=0" frameborder="0" allowfullscreen=""></iframe> | |
621 </p> | |
622 </div> | |
623 <!-- API PAGE --> | |
624 <!-- /apiPage --> | |
625 </div> <!-- /gc-pagecontent --> | |
626 </div> <!-- /g-section --> | |
627 </div> <!-- /codesiteContent --> | |
628 <div id="gc-footer" --=""> | |
629 <div class="text"> | |
630 <p> | |
631 Except as otherwise <a href="http://code.google.com/policies.html#restrictions
">noted</a>, | |
632 the content of this page is licensed under the <a rel="license" href="http://c
reativecommons.org/licenses/by/3.0/">Creative Commons | |
633 Attribution 3.0 License</a>, and code samples are licensed under the | |
634 <a rel="license" href="http://code.google.com/google_bsd_license.html">BSD Lic
ense</a>. | |
635 </p> | |
636 <p> | |
637 ©2011 Google | |
638 </p> | |
639 <!-- begin analytics --> | |
640 <script src="https://www.google-analytics.com/urchin.js" type="text/javascript">
</script> | |
641 <script src="https://www.google-analytics.com/ga.js" type="text/javascript"></sc
ript> | |
642 <script type="text/javascript"> | |
643 // chrome doc tracking | |
644 try { | |
645 var engdocs = _gat._getTracker("YT-10763712-2"); | |
646 engdocs._trackPageview(); | |
647 } catch(err) {} | |
648 // code.google.com site-wide tracking | |
649 try { | |
650 _uacct="UA-18071-1"; | |
651 _uanchor=1; | |
652 _uff=0; | |
653 urchinTracker(); | |
654 } | |
655 catch(e) {/* urchinTracker not available. */} | |
656 </script> | |
657 <!-- end analytics --> | |
658 </div> | |
659 </div> <!-- /gc-footer --> | |
660 </div> <!-- /gc-container --> | |
661 </body></html> | |
OLD | NEW |