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/jstemplate_compiled.js"> 15 </script> 16 <script type="text/javascript" src="js/api_page_generator.js"></script> 17 <script type="text/javascript" src="js/bootstrap.js"></script> 18 <script type="text/javascript" src="js/sidebar.js"></script> 19 <title>Content Scripts - Google Chrome Extensions - Google Code</title></head> 20 <body> <div id="gc-container" class="labs"> 21 <div id="devModeWarning"> 22 You are viewing extension docs in chrome via the 'file:' scheme: are you expecting to see local changes when you refresh? You'll need run chrome with --allow-file-access-from-files. 23 </div> 24 <!-- SUBTEMPLATES: DO NOT MOVE FROM THIS LOCATION --> 25 <!-- In particular, sub-templates that recurse, must be used by allowing 26 jstemplate to make a copy of the template in this section which 27 are not operated on by way of the jsskip="true" --> 28 <div style="display:none"> 29 30 <!-- VALUE --> 31 <div id="valueTemplate"> 32 <dt> 33 <var>paramName</var> 34 <em> 35 36 <!-- TYPE --> 37 <div style="display:inline"> 38 ( 39 <span class="optional">optional</span> 40 <span class="enum">enumerated</span> 41 <span id="typeTemplate"> 42 <span> 43 <a> Type</a> 44 </span> 45 <span> 46 <span> 47 array of <span><span></span></span> 48 </span> 49 <span>paramType</span> 50 <span></span> 51 </span> 52 </span> 53 ) 54 </div> 55 56 </em> 57 </dt> 58 <dd class="todo"> 59 Undocumented. 60 </dd> 61 <dd> 62 Description of this parameter from the json schema. 63 </dd> 64 <dd> 65 This parameter was added in version 66 <b><span></span></b>. 67 You must omit this parameter in earlier versions, 68 and you may omit it in any version. If you require this 69 parameter, the manifest key 70 <a href="manifest.html#minimum_chrome_version">minimum_chrome_version</a> 71 can ensure that your extension won't be run in an earlier browser version. 72 </dd> 73 74 <!-- OBJECT PROPERTIES --> 75 <dd> 76 <dl> 77 <div> 78 <div> 79 </div> 80 </div> 81 </dl> 82 </dd> 83 84 <!-- OBJECT METHODS --> 85 <dd> 86 <div></div> 87 </dd> 88 89 <!-- OBJECT EVENT FIELDS --> 90 <dd> 91 <div></div> 92 </dd> 93 94 <!-- FUNCTION PARAMETERS --> 95 <dd> 96 <div></div> 97 </dd> 98 99 </div> <!-- /VALUE --> 100 101 <div id="functionParametersTemplate"> 102 <h5>Parameters</h5> 103 <dl> 104 <div> 105 <div> 106 </div> 107 </div> 108 </dl> 109 </div> 110 </div> <!-- /SUBTEMPLATES --> 111 112 <a id="top"></a> 113 <div id="skipto"> 114 <a href="#gc-pagecontent">Skip to page content</a> 115 <a href="#gc-toc">Skip to main navigation</a> 116 </div> 117 <!-- API HEADER --> 118 <table id="header" width="100%" cellspacing="0" border="0"> 119 <tbody><tr> 120 <td valign="middle"><a href="http://code.google.com/"><img src="images/code_labs_logo.gif" height="43" width="161" alt="Google Code Labs" style="border:0; margin:0;"></a></td> 121 <td valign="middle" width="100%" style="padding-left:0.6em;"> 122 <form action="http://www.google.com/cse" id="cse" style="margin-top:0.5em"> 123 <div id="gsc-search-box"> 124 <input type="hidden" name="cx" value="002967670403910741006:61_cvzfqtno"> 125 <input type="hidden" name="ie" value="UTF-8"> 126 <input type="text" name="q" value="" size="55"> 127 <input class="gsc-search-button" type="submit" name="sa" value="Search"> 128 <br> 129 <span class="greytext">e.g. "page action" or "tabs"</span> 130 </div> 131 </form> 132 133 <script type="text/javascript" src="http://www.google.com/jsapi"></script> 134 <script type="text/javascript">google.load("elements", "1", {packages: "transliteration"});</script> 135 <script type="text/javascript" src="http://www.google.com/coop/cse/t13n?form=cse&t13n_langs=en"></script> 136 <script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cse&lang=en"></script> 137 </td> 138 </tr> 139 </tbody></table> 140 141 <div id="codesiteContent" class=""> 142 143 <a id="gc-topnav-anchor"></a> 144 <div id="gc-topnav"> 145 <h1>Google Chrome Extensions (<a href="http://code.google.com/labs/">Labs</a>)</h1> 146 <ul id="home" class="gc-topnav-tabs"> 147 <li id="home_link"> 148 <a href="index.html" title="Google Chrome Extensions home page">Home</a> 149 </li> 150 <li id="docs_link"> 151 <a href="docs.html" title="Official Google Chrome Extensions documentation">Docs</a> 152 </li> 153 <li id="faq_link"> 154 <a href="faq.html" title="Answers to frequently asked questions about Google Chrome Extensions">FAQ</a> 155 </li> 156 <li id="samples_link"> 157 <a href="samples.html" title="Sample extensions (with source code)">Samples</a> 158 </li> 159 <li id="group_link"> 160 <a href="http://groups.google.com/a/chromium.org/group/chromium-extensions" title="Google Chrome Extensions developer forum">Group</a> 161 </li> 162 </ul> 163 </div> <!-- end gc-topnav --> 164 165 <div class="g-section g-tpl-170"> 166 <!-- SIDENAV --> 167 <div class="g-unit g-first" id="gc-toc"> 168 <ul> 169 <li><a href="getstarted.html">Getting Started</a></li> 170 <li><a href="overview.html">Overview</a></li> 171 <li><a href="whats_new.html">What's New?</a></li> 172 <li><h2><a href="devguide.html">Developer's Guide</a></h2> 173 <ul> 174 <li>Browser UI 175 <ul> 176 <li><a href="browserAction.html">Browser Actions</a></li> 177 <li><a href="contextMenus.html">Context Menus</a></li> 178 <li><a href="notifications.html">Desktop Notifications</a></li> 179 <li><a href="omnibox.html">Omnibox</a></li> 180 <li><a href="options.html">Options Pages</a></li> 181 <li><a href="override.html">Override Pages</a></li> 182 <li><a href="pageAction.html">Page Actions</a></li> 183 </ul> 184 </li> 185 <li>Browser Interaction 186 <ul> 187 <li><a href="bookmarks.html">Bookmarks</a></li> 188 <li><a href="cookies.html">Cookies</a></li> 189 <li><a href="events.html">Events</a></li> 190 <li><a href="history.html">History</a></li> 191 <li><a href="management.html">Management</a></li> 192 <li><a href="tabs.html">Tabs</a></li> 193 <li><a href="windows.html">Windows</a></li> 194 </ul> 195 </li> 196 <li>Implementation 197 <ul> 198 <li><a href="a11y.html">Accessibility</a></li> 199 <li><a href="background_pages.html">Background Pages</a></li> 200 <li class="leftNavSelected">Content Scripts</li> 201 <li><a href="xhr.html">Cross-Origin XHR</a></li> 202 <li><a href="idle.html">Idle</a></li> 203 <li><a href="i18n.html">Internationalization</a></li> 204 <li><a href="messaging.html">Message Passing</a></li> 205 <li><a href="npapi.html">NPAPI Plugins</a></li> 206 </ul> 207 </li> 208 <li>Finishing 209 <ul> 210 <li><a href="hosting.html">Hosting</a></li> 211 <li><a href="external_extensions.html">Other Deployment Options</a></li> 212 </ul> 213 </li> 214 </ul> 215 </li> 216 <li><h2><a href="apps.html">Packaged Apps</a></h2></li> 217 <li><h2><a href="tutorials.html">Tutorials</a></h2> 218 <ul> 219 <li><a href="tut_debugging.html">Debugging</a></li> 220 <li><a href="tut_analytics.html">Google Analytics</a></li> 221 <li><a href="tut_oauth.html">OAuth</a></li> 222 </ul> 223 </li> 224 <li><h2>Reference</h2> 225 <ul> 226 <li>Formats 227 <ul> 228 <li><a href="manifest.html">Manifest Files</a></li> 229 <li><a href="match_patterns.html">Match Patterns</a></li> 230 </ul> 231 </li> 232 <li><a href="permission_warnings.html">Permission Warnings</a></li> 233 <li><a href="api_index.html">chrome.* APIs</a></li> 234 <li><a href="api_other.html">Other APIs</a></li> 235 </ul> 236 </li> 237 <li><h2><a href="samples.html">Samples</a></h2></li> 238 <div class="line"> </div> 239 <li><h2>More</h2> 240 <ul> 241 <li><a href="http://code.google.com/chrome/webstore/docs/index.html">Chrome Web Store</a></li> 242 <li><a href="http://code.google.com/chrome/apps/docs/developers_guide.html">Hosted Apps</a></li> 243 <li><a href="themes.html">Themes</a></li> 244 </ul> 245 </li> 246 </ul> 247 </div> 248 <script> 249 initToggles(); 250 </script> 251 252 <div class="g-unit" id="gc-pagecontent"> 253 <div id="pageTitle"> 254 <h1 class="page_title">Content Scripts</h1> 255 </div> 256 <!-- TABLE OF CONTENTS --> 257 <div id="toc"> 258 <h2>Contents</h2> 259 <ol> 260 <li> 261 <a href="#registration">Manifest</a> 262 <ol> 263 <li> 264 <a href="#include-exclude-globs">Include and exclude globs</a> 265 </li> 266 </ol> 267 </li><li> 268 <a href="#pi">Programmatic injection</a> 269 <ol> 270 <li style="display: none; "> 271 <a>h3Name</a> 272 </li> 273 </ol> 274 </li><li> 275 <a href="#execution-environment">Execution environment</a> 276 <ol> 277 <li style="display: none; "> 278 <a>h3Name</a> 279 </li> 280 </ol> 281 </li><li> 282 <a href="#host-page-communication">Communication with the embedding page</a> 283 <ol> 284 <li style="display: none; "> 285 <a>h3Name</a> 286 </li> 287 </ol> 288 </li><li> 289 <a href="#security-considerations">Security considerations</a> 290 <ol> 291 <li style="display: none; "> 292 <a>h3Name</a> 293 </li> 294 </ol> 295 </li><li> 296 <a href="#extension-files">Referring to extension files</a> 297 <ol> 298 <li style="display: none; "> 299 <a>h3Name</a> 300 </li> 301 </ol> 302 </li><li> 303 <a href="#examples"> Examples </a> 304 <ol> 305 <li style="display: none; "> 306 <a>h3Name</a> 307 </li> 308 </ol> 309 </li><li> 310 <a href="#videos"> Videos </a> 311 <ol> 312 <li style="display: none; "> 313 <a>h3Name</a> 314 </li> 315 </ol> 316 </li> 317 <li style="display: none; "> 318 <a href="#apiReference">API reference</a> 319 <ol> 320 <li> 321 <a href="#properties">Properties</a> 322 <ol> 323 <li> 324 <a href="#property-anchor">propertyName</a> 325 </li> 326 </ol> 327 </li> 328 <li> 329 <a>Methods</a> 330 <ol> 331 <li> 332 <a href="#method-anchor">methodName</a> 333 </li> 334 </ol> 335 </li> 336 <li> 337 <a>Events</a> 338 <ol> 339 <li> 340 <a href="#event-anchor">eventName</a> 341 </li> 342 </ol> 343 </li> 344 <li> 345 <a href="#types">Types</a> 346 <ol> 347 <li> 348 <a href="#id-anchor">id</a> 349 </li> 350 </ol> 351 </li> 352 </ol> 353 </li> 354 </ol> 355 </div> 356 <!-- /TABLE OF CONTENTS --> 357 358 <!-- Standard content lead-in for experimental API pages --> 359 <p id="classSummary" style="display: none; "> 360 For information on how to use experimental APIs, see the <a href="experimental.html">chrome.experimental.* APIs</a> page. 361 </p> 362 363 <!-- STATIC CONTENT PLACEHOLDER --> 364 <div id="static"><div id="pageData-name" class="pageData">Content Scripts</div> 365 <div id="pageData-showTOC" class="pageData">true</div> 366 367 <p> 368 Content scripts are JavaScript files that run in the context of web pages. 369 By using the standard 370 <a href="http://www.w3.org/TR/DOM-Level-2-HTML/">Document 371 Object Model</a> (DOM), 372 they can read details of the web pages the browser visits, 373 or make changes to them. 374 </p> 375 376 <p> 377 Here are some examples of what content scripts can do: 378 </p> 379 380 <ul> 381 <li>Find unlinked URLs in web pages and convert them into hyperlinks 382 </li><li>Increase the font size to make text more legible 383 </li><li>Find and process <a href="http://microformats.org/">microformat</a> data in the DOM 384 </li></ul> 385 386 <p> 387 However, content scripts have some limitations. 388 They <b>cannot</b>: 389 </p> 390 391 <ul> 392 <li> 393 Use chrome.* APIs 394 (except for parts of 395 <a href="extension.html"><code>chrome.extension</code></a>) 396 </li> 397 <li> 398 Use variables or functions defined by their extension's pages 399 </li> 400 <li> 401 Use variables or functions defined by web pages or by other content scripts 402 </li> 403 <li> 404 Make <a href="xhr.html">cross-site XMLHttpRequests</a> 405 </li> 406 </ul> 407 408 <p> 409 These limitations aren't as bad as they sound. 410 Content scripts can <em>indirectly</em> use the chrome.* APIs, 411 get access to extension data, 412 and request extension actions 413 by exchanging <a href="messaging.html">messages</a> 414 with their parent extension. 415 Content scripts can also 416 <a href="#host-page-communication">communicate with web pages</a> 417 using the shared DOM. 418 For more insight into what content scripts can and can't do, 419 learn about the 420 <a href="#execution-environment">execution environment</a>. 421 </p> 422 423 <h2 id="registration">Manifest</h2> 424 425 <p>If your content script's code should always be injected, 426 register it in the 427 <a href="manifest.html">extension manifest</a> 428 using the <code>content_scripts</code> field, 429 as in the following example. 430 </p> 431 432 <pre>{ 433 "name": "My extension", 434 ... 435 <b>"content_scripts": [ 436 { 437 "matches": ["http://www.google.com/*"], 438 "css": ["mystyles.css"], 439 "js": ["jquery.js", "myscript.js"] 440 } 441 ]</b>, 442 ... 443 }</pre> 444 445 <p> 446 If you want to inject the code only sometimes, 447 use the 448 <a href="manifest.html#permissions"><code>permissions</code></a> field instead, 449 as described in <a href="#pi">Programmatic injection</a>. 450 </p> 451 452 <pre>{ 453 "name": "My extension", 454 ... 455 <b>"permissions": [ 456 "tabs", "http://www.google.com/*" 457 ]</b>, 458 ... 459 }</pre> 460 461 <p> 462 Using the <code>content_scripts</code> field, 463 an extension can insert multiple content scripts into a page; 464 each of these content scripts can have multiple JavaScript and CSS files. 465 Each item in the <code>content_scripts</code> array 466 can have the following properties:</p> 467 468 <table> 469 <tbody><tr> 470 <th>Name</th> 471 <th>Type</th> 472 <th>Description</th> 473 </tr> 474 <tr> 475 <td><code>matches</code></td> 476 <td>array of strings</td> 477 <td><em>Required.</em> 478 Controls the pages this content script will be injected into. 479 See <a href="match_patterns.html">Match Patterns</a> 480 for more details on the syntax of these strings.</td> 481 </tr> 482 <tr> 483 <td><code>css<code></code></code></td> 484 <td>array of strings</td> 485 <td><em>Optional.</em> 486 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 displayed for the page.</td> 487 </tr> 488 <tr> 489 <td><code>js<code></code></code></td> 490 <td><nobr>array of strings</nobr></td> 491 <td><em>Optional.</em> 492 The list of JavaScript files to be injected into matching pages. These are injected in the order they appear in this array.</td> 493 </tr> 494 <tr> 495 <td><code>run_at<code></code></code></td> 496 <td>string</td> 497 <td><em>Optional.</em> 498 Controls when the files in <code>js</code> are injected. Can be "document_start", "document_end", or "document_idle". Defaults to "document_idle". 499 500 <br><br> 501 502 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 is run. 503 504 <br><br> 505 506 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. 507 508 <br><br> 509 510 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.whatwg.org/specs/web-apps/current-work/#handler-onload">window.onload</a></code> event fires. The exact moment of injection depends on how complex the document is and how long it is taking to load, and is optimized for page load speed. 511 512 <br><br> 513 514 <b>Note:</b> With "document_idle", content scripts may not necessarily receive the <code>window.onload</code> event, because they may run after it has 515 already fired. In most cases, listening for the <code>onload</code> event is unnecessary for content scripts running at "document_idle" because they are guaranteed 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 already fired by using the <code><a href="http://www.whatwg.org/specs/web-apps/current-work/#dom-document-readystate">document.readyState</a></code> property.</td> 516 </tr> 517 <tr> 518 <td><code>all_frames<code></code></code></td> 519 <td>boolean</td> 520 <td><em>Optional.</em> 521 Controls whether the content script runs in all frames of the matching page, or only the top frame. 522 <br><br> 523 Defaults to <code>false</code>, meaning that only the top frame is matched.</td> 524 </tr> 525 <tr> 526 <td><code>include_globs</code></td> 527 <td>array of string</td> 528 <td><em>Optional.</em> 529 Applied after <code>matches</code> to control the pages that this content script will be injected into. Intended to emulate the <a href="http://wiki.greasespot.net/Metadata_Block#.40include"><code>@include</code></a> Greasemonkey keyword. See <a href="#include-exclude-globs">Include and exclude globs</a> below for more details.</td> 530 </tr> 531 <tr> 532 <td><code>exclude_globs</code></td> 533 <td>array of string</td> 534 <td><em>Optional.</em> 535 Applied after <code>matches</code> to control the pages that this content script will be injected into. Intended to emulate the <a href="http://wiki.greasespot.net/Metadata_Block#.40include"><code>@exclude</code></a> Greasemonkey keyword. See <a href="#include-exclude-globs">Include and exclude globs</a> below for more details.</td> 536 </tr> 537 </tbody></table> 538 539 <h3 id="include-exclude-globs">Include and exclude globs</h3> 540 541 <p> 542 The content script will be injected into a page if its URL matches any <code>matches</code> pattern and any <code>include_globs</code> pattern, as long as the URL doesn't also match an <code>exclude_globs</code> pattern. Because the <code>matches</code> property is required, <code>include_globs</code> and <code>exclude_globs</code> can only be used to limit which pages will be affected. 543 </p> 544 545 <p></p> 546 However, these glob properties follow a different syntax than <code>matches</code>, which is much more flexible. Acceptable strings are URLs that may contain "wildcard" asterisks and question marks. The asterisk (*) is used to match any string of any length (including the empty string); the question mark (?) is used to match any single character. 547 <p></p> 548 549 <p> 550 For example, the glob "http://???.example.com/foo/*" matches any of the following: 551 </p> 552 <ul> 553 <li>"http://www.example.com/foo/bar"</li> 554 <li>"http://the.example.com/foo/"</li> 555 </ul> 556 <p> 557 However, it does <em>not</em> match the following: 558 </p> 559 <ul> 560 <li>"http://my.example.com/foo/bar"</li> 561 <li>"http://example.com/foo/"</li> 562 <li>"http://www.example.com/foo"</li> 563 </ul> 564 565 <h2 id="pi">Programmatic injection</h2> 566 567 <p> 568 Inserting code into a page programmatically is useful 569 when your JavaScript or CSS code 570 shouldn't be injected into every single page 571 that matches the pattern 572 for example, if you want a script to run 573 only when the user clicks a browser action's icon. 574 </p> 575 576 <p> 577 To insert code into a page, 578 your extension must have 579 <a href="xhr.html#requesting-permission">cross-origin permissions</a> 580 for the page. 581 It also must be able to use the <code>chrome.tabs</code> module. 582 You can get both kinds of permission 583 using the manifest file's 584 <a href="manifest.html#permissions">permissions</a> field. 585 </p> 586 587 <p> 588 Once you have permissions set up, 589 you can inject JavaScript into a page by calling 590 <a href="tabs.html#method-executeScript"><code>executeScript()</code></a>. 591 To inject CSS, use 592 <a href="tabs.html#method-insertCSS"><code>insertCSS()</code></a>. 593 </p> 594 595 <p> 596 The following code 597 (from the 598 <a href="http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/docs/examples/api/browserAction/make_page_red/">make_page_red</a> example) 599 reacts to a user click 600 by inserting JavaScript into the current tab's page 601 and executing the script. 602 </p> 603 604 <pre><em>/* in background.html */</em> 605 chrome.browserAction.onClicked.addListener(function(tab) { 606 chrome.tabs.executeScript(null, 607 {code:"document.body.bgColor='red'"}); 608 }); 609 610 <em>/* in manifest.json */</em> 611 "permissions": [ 612 "tabs", "http://*/*" 613 ], 614 </pre> 615 616 <p> 617 When the browser is displaying an HTTP page 618 and the user clicks this extension's browser action, 619 the extension sets the page's <code>bgcolor</code> property to 'red'. 620 The result, 621 unless the page has CSS that sets the background color, 622 is that the page turns red. 623 </p> 624 625 <p> 626 Usually, instead of inserting code directly (as in the previous sample), 627 you put the code in a file. 628 You inject the file's contents like this: 629 </p> 630 631 <pre>chrome.tabs.executeScript(null, {file: "content_script.js"});</pre> 632 633 634 <h2 id="execution-environment">Execution environment</h2> 635 636 <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 to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on. The same is true in reverse: JavaScript running on the page cannot call any functions or access any variables defined by content scripts. 637 638 </p><p>For example, consider this simple page: 639 640 </p><pre>hello.html 641 ========== 642 <html> 643 <button id="mybutton">click me</button> 644 <script> 645 var greeting = "hello, "; 646 var button = document.getElementById("mybutton"); 647 button.person_name = "Bob"; 648 button.addEventListener("click", function() { 649 alert(greeting + button.person_name + "."); 650 }, false); 651 </script> 652 </html></pre> 653 654 <p>Now, suppose this content script was injected into hello.html: 655 656 </p><pre>contentscript.js 657 ================ 658 var greeting = "hola, "; 659 var button = document.getElementById("mybutton"); 660 button.person_name = "Roberto"; 661 button.addEventListener("click", function() { 662 alert(greeting + button.person_name + "."); 663 }, false); 664 </pre> 665 666 <p>Now, if the button is pressed, you will see both greetings. 667 668 </p><p>Isolated worlds allow each content script to make changes to its JavaScript environment without worrying about conflicting with the page or with other content scripts. For example, a content script could include JQuery v1 and the page could include JQuery v2, and they wouldn't conflict with each other. 669 670 </p><p>Another important benefit of isolated worlds is that they completely separate the JavaScript on the page from the JavaScript in extensions. This allows us to offer extra functionality to content scripts that should not be accessible from web pages without worrying about web pages accessing it. 671 672 673 </p><h2 id="host-page-communication">Communication with the embedding page</h2> 674 675 <p>Although the execution environments of content scripts and the pages that host 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 the content script), it must do so through the shared DOM.</p> 676 677 <p>An example can be accomplished using custom DOM events and storing data in a known location. Consider: </p> 678 679 <pre>http://foo.com/example.html 680 =========================== 681 var customEvent = document.createEvent('Event'); 682 customEvent.initEvent('myCustomEvent', true, true); 683 684 function fireCustomEvent(data) { 685 hiddenDiv = document.getElementById('myCustomEventDiv'); 686 hiddenDiv.innerText = data 687 hiddenDiv.dispatchEvent(customEvent); 688 }</pre> 689 690 <pre>contentscript.js 691 ================ 692 var port = chrome.extension.connect(); 693 694 document.getElementById('myCustomEventDiv').addEventListener('myCustomEvent', function() { 695 var eventData = document.getElementById('myCustomEventDiv').innerText; 696 port.postMessage({message: "myCustomEvent", values: eventData}); 697 });</pre> 698 699 <p>In the above example, example.html (which is not a part of the extension) creates a custom event and then can decide to fire the event by setting the event data to a known location in the DOM and then dispatching the custom event. The content script listens for the name of the custom event on the known element and handles the event by inspecting the data of the element, and turning around to post the message to the extension process. In this way the page establishes a line of communication to the extension. The reverse is possible through similar means.</p> 700 701 <h2 id="security-considerations">Security considerations</h2> 702 703 <p>When writing a content script, you should be aware of two security issues. 704 First, be careful not to introduce security vulnerabilities into the web site 705 your content script is injected into. For example, if your content script 706 receives content from another web site (e.g., by <a href="messaging.html">asking your background page to make an 707 XMLHttpRequest</a>), be careful to filter that content for <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">cross-site 708 scripting</a> attacks before injecting the content into the current page. 709 For example, prefer to inject content via innerText rather than innerHTML. 710 Be especially careful when retrieving HTTP content on an HTTPS page because 711 the HTTP content might have been corrupted by a network <a href="http://en.wikipedia.org/wiki/Man-in-the-middle_attack">"man-in-the-middle"</a> 712 if the user is on a hostile network.</p> 713 714 <p>Second, although running your content script in an isolated world provides 715 some protection from the web page, a malicious web page might still be able 716 to attack your content script if you use content from the web page 717 indiscriminately. For example, the following patterns are dangerous: 718 </p><pre>contentscript.js 719 ================ 720 var data = document.getElementById("json-data") 721 // WARNING! Might be evaluating an evil script! 722 var parsed = eval("(" + data + ")") 723 724 contentscript.js 725 ================ 726 var elmt_id = ... 727 // WARNING! elmt_id might be "); ... evil script ... //"! 728 window.setTimeout("animate(" + elmt_id + ")", 200); 729 </pre> 730 <p>Instead, prefer safer APIs that do not run scripts:</p> 731 <pre>contentscript.js 732 ================ 733 var data = document.getElementById("json-data") 734 // JSON.parse does not evaluate the attacker's scripts. 735 var parsed = JSON.parse(data) 736 737 contentscript.js 738 ================ 739 var elmt_id = ... 740 // The closure form of setTimeout does not evaluate scripts. 741 window.setTimeout(function() { 742 animate(elmt_id); 743 }, 200); 744 </pre> 745 746 <h2 id="extension-files">Referring to extension files</h2> 747 748 <p> 749 Get the URL of an extension's file using 750 <code>chrome.extension.getURL()</code>. 751 You can use the result 752 just like you would any other URL, 753 as the following code shows. 754 </p> 755 756 757 <pre><em>//Code for displaying <extensionDir>/images/myimage.png:</em> 758 var imgURL = <b>chrome.extension.getURL("images/myimage.png")</b>; 759 document.getElementById("someImage").src = imgURL; 760 </pre> 761 762 <h2 id="examples"> Examples </h2> 763 764 <p> 765 The 766 <a href="http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/docs/examples/howto/contentscript_xhr">contentscript_xhr</a> example 767 shows how an extension can perform 768 cross-site requests for its content script. 769 You can find other simple examples of communication via messages in the 770 <a href="http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/docs/examples/api/messaging/">examples/api/messaging</a> 771 directory. 772 </p> 773 774 <p> 775 See 776 <a href="http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/docs/examples/api/browserAction/make_page_red/">make_page_red</a> and 777 <a href="http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/docs/examples/extensions/email_this_page/">email_this_page</a> 778 for examples of programmatic injection. 779 780 </p> 781 782 <p> 783 For more examples and for help in viewing the source code, see 784 <a href="samples.html">Samples</a>. 785 </p> 786 787 <h2 id="videos"> Videos </h2> 788 789 <p> 790 The following videos discuss concepts that are important for content scripts. 791 The first video describes content scripts and isolated worlds. 792 </p> 793 794 <p> 795 <iframe title="YouTube video player" width="640" height="390" src="http://www.youtube.com/embed/laLudeUmXHM?rel=0" frameborder="0" allowfullscreen=""></iframe> 796 </p> 797 798 <p> 799 The next video describes message passing, 800 featuring an example of a content script 801 sending a request to its parent extension. 802 </p> 803 804 <p> 805 <iframe title="YouTube video player" width="640" height="390" src="http://www.youtube.com/embed/B4M_a7xejYI?rel=0" frameborder="0" allowfullscreen=""></iframe> 806 </p> 807 </div> 808 809 <!-- API PAGE --> 810 <div class="apiPage" style="display: none; "> 811 <a name="apiReference"></a> 812 <h2>API reference: chrome.apiname </h2> 813 814 <!-- PROPERTIES --> 815 <div class="apiGroup"> 816 <a name="properties"></a> 817 <h3 id="properties">Properties</h3> 818 819 <div> 820 <a></a> 821 <h4>getLastError</h4> 822 <div class="summary"> 823 <!-- Note: intentionally longer 80 columns --> 824 <span>chrome.extension</span><span>lastError</span> 825 </div> 826 <div> 827 </div> 828 </div> 829 830 </div> <!-- /apiGroup --> 831 832 <!-- METHODS --> 833 <div id="methodsTemplate" class="apiGroup"> 834 <a></a> 835 <h3>Methods</h3> 836 837 <!-- iterates over all functions --> 838 <div class="apiItem"> 839 <a></a> <!-- method-anchor --> 840 <h4>method name</h4> 841 842 <div class="summary"><span>void</span> 843 <!-- Note: intentionally longer 80 columns --> 844 <span>chrome.module.methodName</span>(<span><span>, </span><span></span> 845 <var><span></span></var></span>)</div> 846 847 <div class="description"> 848 <p class="todo">Undocumented.</p> 849 <p> 850 A description from the json schema def of the function goes here. 851 </p> 852 853 <!-- PARAMETERS --> 854 <h4>Parameters</h4> 855 <dl> 856 <div> 857 <div> 858 </div> 859 </div> 860 </dl> 861 862 <!-- RETURNS --> 863 <h4>Returns</h4> 864 <dl> 865 <div> 866 <div> 867 </div> 868 </div> 869 </dl> 870 871 <!-- CALLBACK --> 872 <div> 873 <div> 874 <h4>Callback function</h4> 875 <p> 876 The callback <em>parameter</em> should specify a function 877 that looks like this: 878 </p> 879 <p> 880 If you specify the <em>callback</em> parameter, it should 881 specify a function that looks like this: 882 </p> 883 884 <!-- Note: intentionally longer 80 columns --> 885 <pre>function(<span>Type param1, Type param2</span>) <span class="subdued">{...}</span>;</pre> 886 <dl> 887 <div> 888 <div> 889 </div> 890 </div> 891 </dl> 892 </div> 893 </div> 894 895 <!-- MIN_VERSION --> 896 <p> 897 This function was added in version <b><span></span></b>. 898 If you require this function, the manifest key 899 <a href="manifest.html#minimum_chrome_version">minimum_chrome_version</a> 900 can ensure that your extension won't be run in an earlier browser version. 901 </p> 902 </div> <!-- /description --> 903 904 </div> <!-- /apiItem --> 905 906 </div> <!-- /apiGroup --> 907 908 <!-- EVENTS --> 909 <div id="eventsTemplate" class="apiGroup"> 910 <a></a> 911 <h3>Events</h3> 912 <!-- iterates over all events --> 913 <div class="apiItem"> 914 <a></a> 915 <h4>event name</h4> 916 917 <div class="summary"> 918 <!-- Note: intentionally longer 80 columns --> 919 <span class="subdued">chrome.bookmarks</span><span>onEvent</span><span class="subdued">.addListener</span>(function(<span>Type param1, Type param2</span>) <span class="subdued">{...}</span>); 920 </div> 921 922 <div class="description"> 923 <p class="todo">Undocumented.</p> 924 <p> 925 A description from the json schema def of the event goes here. 926 </p> 927 928 <!-- PARAMETERS --> 929 <div> 930 <h4>Parameters</h4> 931 <dl> 932 <div> 933 <div> 934 </div> 935 </div> 936 </dl> 937 </div> 938 </div> <!-- /decription --> 939 940 </div> <!-- /apiItem --> 941 942 </div> <!-- /apiGroup --> 943 944 <!-- TYPES --> 945 <div class="apiGroup"> 946 <a name="types"></a> 947 <h3 id="types">Types</h3> 948 949 <!-- iterates over all types --> 950 <div class="apiItem"> 951 <a></a> 952 <h4>type name</h4> 953 954 <div> 955 </div> 956 957 </div> <!-- /apiItem --> 958 959 </div> <!-- /apiGroup --> 960 961 </div> <!-- /apiPage --> 962 </div> <!-- /gc-pagecontent --> 963 </div> <!-- /g-section --> 964 </div> <!-- /codesiteContent --> 965 <div id="gc-footer" --=""> 966 <div class="text"> 967 <p> 968 Except as otherwise <a href="http://code.google.com/policies.html#restrictions">noted</a>, 969 the content of this page is licensed under the <a rel="license" href="http://creativecommons.org/licenses/by/3.0/">Creative Commons 970 Attribution 3.0 License</a>, and code samples are licensed under the 971 <a rel="license" href="http://code.google.com/google_bsd_license.html">BSD License</a>. 972 </p> 973 <p> 974 2011 Google 975 </p> 976 977 <!-- begin analytics --> 978 <script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script> 979 <script src="http://www.google-analytics.com/ga.js" type="text/javascript"></script> 980 981 <script type="text/javascript"> 982 // chrome doc tracking 983 try { 984 var engdocs = _gat._getTracker("YT-10763712-2"); 985 engdocs._trackPageview(); 986 } catch(err) {} 987 988 // code.google.com site-wide tracking 989 try { 990 _uacct="UA-18071-1"; 991 _uanchor=1; 992 _uff=0; 993 urchinTracker(); 994 } 995 catch(e) {/* urchinTracker not available. */} 996 </script> 997 <!-- end analytics --> 998 </div> 999 </div> <!-- /gc-footer --> 1000 </div> <!-- /gc-container --> 1001 </body></html> 1002