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