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