OLD | NEW |
(Empty) | |
| 1 <h1>Content Scripts</h1> |
| 2 |
| 3 |
| 4 <p> |
| 5 Content scripts are JavaScript files that run in the context of web pages. |
| 6 By using the standard |
| 7 <a href="http://www.w3.org/TR/DOM-Level-2-HTML/">Document |
| 8 Object Model</a> (DOM), |
| 9 they can read details of the web pages the browser visits, |
| 10 or make changes to them. |
| 11 </p> |
| 12 |
| 13 <p> |
| 14 Here are some examples of what content scripts can do: |
| 15 </p> |
| 16 |
| 17 <ul> |
| 18 <li>Find unlinked URLs in web pages and convert them into hyperlinks |
| 19 <li>Increase the font size to make text more legible |
| 20 <li>Find and process <a href="http://microformats.org/">microformat</a> data i
n the DOM |
| 21 </ul> |
| 22 |
| 23 <p> |
| 24 However, content scripts have some limitations. |
| 25 They <b>cannot</b>: |
| 26 </p> |
| 27 |
| 28 <ul> |
| 29 <li> |
| 30 Use chrome.* APIs |
| 31 (except for parts of |
| 32 <a href="extension.html"><code>chrome.extension</code></a>) |
| 33 </li> |
| 34 <li> |
| 35 Use variables or functions defined by their extension's pages |
| 36 </li> |
| 37 <li> |
| 38 Use variables or functions defined by web pages or by other content scripts |
| 39 </li> |
| 40 </ul> |
| 41 |
| 42 <p> |
| 43 These limitations aren't as bad as they sound. |
| 44 Content scripts can <em>indirectly</em> use the chrome.* APIs, |
| 45 get access to extension data, |
| 46 and request extension actions |
| 47 by exchanging <a href="messaging.html">messages</a> |
| 48 with their parent extension. |
| 49 Content scripts can also |
| 50 make <a href="xhr.html">cross-site XMLHttpRequests</a> |
| 51 to the same sites as their parent extensions, |
| 52 and they can |
| 53 <a href="#host-page-communication">communicate with web pages</a> |
| 54 using the shared DOM. |
| 55 For more insight into what content scripts can and can't do, |
| 56 learn about the |
| 57 <a href="#execution-environment">execution environment</a>. |
| 58 </p> |
| 59 |
| 60 <h2 id="registration">Manifest</h2> |
| 61 |
| 62 <p>If your content script's code should always be injected, |
| 63 register it in the |
| 64 <a href="manifest.html">extension manifest</a> |
| 65 using the <code>content_scripts</code> field, |
| 66 as in the following example. |
| 67 </p> |
| 68 |
| 69 <pre>{ |
| 70 "name": "My extension", |
| 71 ... |
| 72 <b>"content_scripts": [ |
| 73 { |
| 74 "matches": ["http://www.google.com/*"], |
| 75 "css": ["mystyles.css"], |
| 76 "js": ["jquery.js", "myscript.js"] |
| 77 } |
| 78 ]</b>, |
| 79 ... |
| 80 }</pre> |
| 81 |
| 82 <p> |
| 83 If you want to inject the code only sometimes, |
| 84 use the |
| 85 <a href="manifest.html#permissions"><code>permissions</code></a> field instead, |
| 86 as described in <a href="#pi">Programmatic injection</a>. |
| 87 </p> |
| 88 |
| 89 <pre>{ |
| 90 "name": "My extension", |
| 91 ... |
| 92 <b>"permissions": [ |
| 93 "tabs", "http://www.google.com/*" |
| 94 ]</b>, |
| 95 ... |
| 96 }</pre> |
| 97 |
| 98 <p> |
| 99 Using the <code>content_scripts</code> field, |
| 100 an extension can insert multiple content scripts into a page; |
| 101 each of these content scripts can have multiple JavaScript and CSS files. |
| 102 Each item in the <code>content_scripts</code> array |
| 103 can have the following properties:</p> |
| 104 |
| 105 <table> |
| 106 <tr> |
| 107 <th>Name</th> |
| 108 <th>Type</th> |
| 109 <th>Description</th> |
| 110 </tr> |
| 111 <tr> |
| 112 <td><code>matches</code></td> |
| 113 <td>array of strings</td> |
| 114 <td><em>Required.</em> |
| 115 Specifies which pages this content script will be injected into. |
| 116 See <a href="match_patterns.html">Match Patterns</a> |
| 117 for more details on the syntax of these strings |
| 118 and <a href="#match-patterns-globs">Match patterns and globs</a> |
| 119 for information on how to exclude URLs.</td> |
| 120 </tr> |
| 121 <tr> |
| 122 <td><code>exclude_matches</code></td> |
| 123 <td>array of strings</td> |
| 124 <td><em>Optional.</em> |
| 125 Excludes pages that this content script would otherwise be |
| 126 injected into. |
| 127 See <a href="match_patterns.html">Match Patterns</a> |
| 128 for more details on the syntax of these strings |
| 129 and <a href="#match-patterns-globs">Match patterns and globs</a> |
| 130 for information on how to exclude URLs.</td> |
| 131 </tr> |
| 132 <tr> |
| 133 <td><code>css<code></td> |
| 134 <td>array of strings</td> |
| 135 <td><em>Optional.</em> |
| 136 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> |
| 137 </tr> |
| 138 <tr> |
| 139 <td><code>js<code></td> |
| 140 <td><nobr>array of strings</nobr></td> |
| 141 <td><em>Optional.</em> |
| 142 The list of JavaScript files to be injected into matching pages. These are i
njected in the order they appear in this array.</td> |
| 143 </tr> |
| 144 <tr id="run_at"> |
| 145 <td><code>run_at<code></td> |
| 146 <td>string</td> |
| 147 <td><em>Optional.</em> |
| 148 Controls when the files in <code>js</code> are injected. Can be "document_st
art", "document_end", or "document_idle". Defaults to "document_idle". |
| 149 |
| 150 <br><br> |
| 151 |
| 152 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. |
| 153 |
| 154 <br><br> |
| 155 |
| 156 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. |
| 157 |
| 158 <br><br> |
| 159 |
| 160 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. |
| 161 |
| 162 <br><br> |
| 163 |
| 164 <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 |
| 165 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> |
| 166 </tr> |
| 167 <tr> |
| 168 <td><code>all_frames<code></td> |
| 169 <td>boolean</td> |
| 170 <td><em>Optional.</em> |
| 171 Controls whether the content script runs in all frames of the matching page,
or only the top frame. |
| 172 <br><br> |
| 173 Defaults to <code>false</code>, meaning that only the top frame is matched.<
/td> |
| 174 </tr> |
| 175 <tr> |
| 176 <td><code>include_globs</code></td> |
| 177 <td>array of string</td> |
| 178 <td><em>Optional.</em> |
| 179 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. |
| 180 See <a href="#match-patterns-globs">Match patterns and globs</a> below for m
ore details.</td> |
| 181 </tr> |
| 182 <tr> |
| 183 <td><code>exclude_globs</code></td> |
| 184 <td>array of string</td> |
| 185 <td><em>Optional.</em> |
| 186 Applied after <code>matches</code> to exclude URLs that match this glob. |
| 187 Intended to emulate the <a href="http://wiki.greasespot.net/Metadata_Block#.
40include"><code>@exclude</code></a> Greasemonkey keyword. |
| 188 See <a href="#match-patterns-globs">Match patterns and globs</a> below for m
ore details.</td> |
| 189 </tr> |
| 190 </table> |
| 191 |
| 192 <h3 id="match-patterns-globs">Match patterns and globs</h3> |
| 193 |
| 194 <p> |
| 195 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. |
| 196 |
| 197 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. |
| 198 </p> |
| 199 |
| 200 <p> |
| 201 For example, assume <code>matches</code> is <code>["http://*.nytimes.com/*"]</co
de>: |
| 202 </p> |
| 203 <ul> |
| 204 <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> |
| 205 <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> |
| 206 <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> |
| 207 </ul> |
| 208 <p> |
| 209 |
| 210 <p> |
| 211 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. |
| 212 </p> |
| 213 |
| 214 <p> |
| 215 For example, the glob "http://???.example.com/foo/*" matches any of the followin
g: |
| 216 </p> |
| 217 <ul> |
| 218 <li>"http://www.example.com/foo/bar"</li> |
| 219 <li>"http://the.example.com/foo/"</li> |
| 220 </ul> |
| 221 <p> |
| 222 However, it does <em>not</em> match the following: |
| 223 </p> |
| 224 <ul> |
| 225 <li>"http://my.example.com/foo/bar"</li> |
| 226 <li>"http://example.com/foo/"</li> |
| 227 <li>"http://www.example.com/foo"</li> |
| 228 </ul> |
| 229 |
| 230 <h2 id="pi">Programmatic injection</h2> |
| 231 |
| 232 <p> |
| 233 Inserting code into a page programmatically is useful |
| 234 when your JavaScript or CSS code |
| 235 shouldn't be injected into every single page |
| 236 that matches the pattern — |
| 237 for example, if you want a script to run |
| 238 only when the user clicks a browser action's icon. |
| 239 </p> |
| 240 |
| 241 <p> |
| 242 To insert code into a page, |
| 243 your extension must have |
| 244 <a href="xhr.html#requesting-permission">cross-origin permissions</a> |
| 245 for the page. |
| 246 It also must be able to use the <code>chrome.tabs</code> module. |
| 247 You can get both kinds of permission |
| 248 using the manifest file's |
| 249 <a href="manifest.html#permissions">permissions</a> field. |
| 250 </p> |
| 251 |
| 252 <p> |
| 253 Once you have permissions set up, |
| 254 you can inject JavaScript into a page by calling |
| 255 <a href="tabs.html#method-executeScript"><code>executeScript()</code></a>. |
| 256 To inject CSS, use |
| 257 <a href="tabs.html#method-insertCSS"><code>insertCSS()</code></a>. |
| 258 </p> |
| 259 |
| 260 <p> |
| 261 The following code |
| 262 (from the |
| 263 <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) |
| 264 reacts to a user click |
| 265 by inserting JavaScript into the current tab's page |
| 266 and executing the script. |
| 267 </p> |
| 268 |
| 269 <pre> |
| 270 <em>/* in background.html */</em> |
| 271 chrome.browserAction.onClicked.addListener(function(tab) { |
| 272 chrome.tabs.executeScript(null, |
| 273 {code:"document.body.bgColor='red'"}); |
| 274 }); |
| 275 |
| 276 <em>/* in manifest.json */</em> |
| 277 "permissions": [ |
| 278 "tabs", "http://*/*" |
| 279 ], |
| 280 </pre> |
| 281 |
| 282 <p> |
| 283 When the browser is displaying an HTTP page |
| 284 and the user clicks this extension's browser action, |
| 285 the extension sets the page's <code>bgcolor</code> property to 'red'. |
| 286 The result, |
| 287 unless the page has CSS that sets the background color, |
| 288 is that the page turns red. |
| 289 </p> |
| 290 |
| 291 <p> |
| 292 Usually, instead of inserting code directly (as in the previous sample), |
| 293 you put the code in a file. |
| 294 You inject the file's contents like this: |
| 295 </p> |
| 296 |
| 297 <pre>chrome.tabs.executeScript(null, {file: "content_script.js"});</pre> |
| 298 |
| 299 |
| 300 <h2 id="execution-environment">Execution environment</h2> |
| 301 |
| 302 <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. |
| 303 |
| 304 <p>For example, consider this simple page: |
| 305 |
| 306 <pre>hello.html |
| 307 ========== |
| 308 <html> |
| 309 <button id="mybutton">click me</button> |
| 310 <script> |
| 311 var greeting = "hello, "; |
| 312 var button = document.getElementById("mybutton"); |
| 313 button.person_name = "Bob"; |
| 314 button.addEventListener("click", function() { |
| 315 alert(greeting + button.person_name + "."); |
| 316 }, false); |
| 317 </script> |
| 318 </html></pre> |
| 319 |
| 320 <p>Now, suppose this content script was injected into hello.html: |
| 321 |
| 322 <pre>contentscript.js |
| 323 ================ |
| 324 var greeting = "hola, "; |
| 325 var button = document.getElementById("mybutton"); |
| 326 button.person_name = "Roberto"; |
| 327 button.addEventListener("click", function() { |
| 328 alert(greeting + button.person_name + "."); |
| 329 }, false); |
| 330 </pre> |
| 331 |
| 332 <p>Now, if the button is pressed, you will see both greetings. |
| 333 |
| 334 <p>Isolated worlds allow each content script to make changes to its JavaScript e
nvironment without worrying about conflicting with the page or with other conten
t scripts. For example, a content script could include JQuery v1 and the page co
uld include JQuery v2, and they wouldn't conflict with each other. |
| 335 |
| 336 <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. |
| 337 |
| 338 |
| 339 <h2 id="host-page-communication">Communication with the embedding page</h2> |
| 340 |
| 341 <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> |
| 342 <p>An example can be accomplished using window.postMessage (or window.webkitPost
Message for Transferable objects):</p> |
| 343 <pre>contentscript.js |
| 344 ================ |
| 345 var port = chrome.extension.connect(); |
| 346 |
| 347 window.addEventListener("message", function(event) { |
| 348 // We only accept messages from ourselves |
| 349 if (event.source != window) |
| 350 return; |
| 351 |
| 352 if (event.data.type && (event.data.type == "FROM_PAGE")) { |
| 353 console.log("Content script received: " + event.data.text); |
| 354 port.postMessage(event.data.text); |
| 355 } |
| 356 }, false);</pre> |
| 357 <pre>http://foo.com/example.html |
| 358 =========================== |
| 359 document.getElementById("theButton").addEventListener("click", function() { |
| 360 window.postMessage({ type: "FROM_PAGE", text: "Hello from the webpage!" }, "
*"); |
| 361 }, false);</pre> |
| 362 <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> |
| 363 |
| 364 <h2 id="security-considerations">Security considerations</h2> |
| 365 |
| 366 <p>When writing a content script, you should be aware of two security issues. |
| 367 First, be careful not to introduce security vulnerabilities into the web site |
| 368 your content script is injected into. For example, if your content script |
| 369 receives content from another web site (for example, by making an <a |
| 370 href="messaging.html">XMLHttpRequest</a>), |
| 371 be careful to filter that content for <a |
| 372 href="http://en.wikipedia.org/wiki/Cross-site_scripting">cross-site |
| 373 scripting</a> attacks before injecting the content into the current page. |
| 374 For example, prefer to inject content via innerText rather than innerHTML. |
| 375 Be especially careful when retrieving HTTP content on an HTTPS page because |
| 376 the HTTP content might have been corrupted by a network <a |
| 377 href="http://en.wikipedia.org/wiki/Man-in-the-middle_attack">"man-in-the-middle"
</a> |
| 378 if the user is on a hostile network.</p> |
| 379 |
| 380 <p>Second, although running your content script in an isolated world provides |
| 381 some protection from the web page, a malicious web page might still be able |
| 382 to attack your content script if you use content from the web page |
| 383 indiscriminately. For example, the following patterns are dangerous: |
| 384 <pre>contentscript.js |
| 385 ================ |
| 386 var data = document.getElementById("json-data") |
| 387 // WARNING! Might be evaluating an evil script! |
| 388 var parsed = eval("(" + data + ")") |
| 389 |
| 390 contentscript.js |
| 391 ================ |
| 392 var elmt_id = ... |
| 393 // WARNING! elmt_id might be "); ... evil script ... //"! |
| 394 window.setTimeout("animate(" + elmt_id + ")", 200); |
| 395 </pre> |
| 396 <p>Instead, prefer safer APIs that do not run scripts:</p> |
| 397 <pre>contentscript.js |
| 398 ================ |
| 399 var data = document.getElementById("json-data") |
| 400 // JSON.parse does not evaluate the attacker's scripts. |
| 401 var parsed = JSON.parse(data) |
| 402 |
| 403 contentscript.js |
| 404 ================ |
| 405 var elmt_id = ... |
| 406 // The closure form of setTimeout does not evaluate scripts. |
| 407 window.setTimeout(function() { |
| 408 animate(elmt_id); |
| 409 }, 200); |
| 410 </pre> |
| 411 |
| 412 <h2 id="extension-files">Referring to extension files</h2> |
| 413 |
| 414 <p> |
| 415 Get the URL of an extension's file using |
| 416 <code>chrome.extension.getURL()</code>. |
| 417 You can use the result |
| 418 just like you would any other URL, |
| 419 as the following code shows. |
| 420 </p> |
| 421 |
| 422 |
| 423 <pre> |
| 424 <em>//Code for displaying <extensionDir>/images/myimage.png:</em> |
| 425 var imgURL = <b>chrome.extension.getURL("images/myimage.png")</b>; |
| 426 document.getElementById("someImage").src = imgURL; |
| 427 </pre> |
| 428 |
| 429 <h2 id="examples"> Examples </h2> |
| 430 |
| 431 <p> |
| 432 You can find many |
| 433 <a href="samples.html#script">examples that use content scripts</a>. |
| 434 A simple example of communication via messages is in the |
| 435 <a href="samples.html#51a83d2ba3a32e3ff1bdb624d4e18ccec4c4038e">timer sample</a>
. |
| 436 See <a href="samples.html#ede3c47b7757245be42ec33fd5ca63df4b490066">make_page_re
d</a> and |
| 437 <a href="samples.html#028eb5364924344029bcbe1d527f132fc72b34e5">email_this_page<
/a> |
| 438 for examples of programmatic injection. |
| 439 </p> |
| 440 |
| 441 |
| 442 <h2 id="videos"> Videos </h2> |
| 443 |
| 444 <p> |
| 445 The following videos discuss concepts that are important for content scripts. |
| 446 The first video describes content scripts and isolated worlds. |
| 447 </p> |
| 448 |
| 449 <p> |
| 450 <iframe title="YouTube video player" width="640" height="390" src="http://www.yo
utube.com/embed/laLudeUmXHM?rel=0" frameborder="0" allowfullscreen></iframe> |
| 451 </p> |
| 452 |
| 453 <p> |
| 454 The next video describes message passing, |
| 455 featuring an example of a content script |
| 456 sending a request to its parent extension. |
| 457 </p> |
| 458 |
| 459 <p> |
| 460 <iframe title="YouTube video player" width="640" height="390" src="http://www.yo
utube.com/embed/B4M_a7xejYI?rel=0" frameborder="0" allowfullscreen></iframe> |
| 461 </p> |
OLD | NEW |