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