1 <h1>Content Scripts
</h1>
5 Content scripts are JavaScript files that run in the context of web pages.
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.
14 Here are some examples of what content scripts can do:
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 in the DOM
24 However, content scripts have some limitations.
30 Use chrome.* APIs, with the exception of:
31 <ul id=
"content_script_supported_nodes">
32 {{#api:content_scripts}}
36 ({{#n:api.restrictedTo}}
37 $(ref:{{api.name}}.{{n.node}} {{n.node}})
38 {{^n.last}},{{/n.last}}
39 {{/api.restrictedTo}})
46 Use variables or functions defined by their extension's pages
49 Use variables or functions defined by web pages or by other content scripts
54 These limitations aren't as bad as they sound.
55 Content scripts can
<em>indirectly
</em> use the chrome.* APIs,
56 get access to extension data,
57 and request extension actions
58 by exchanging
<a href=
"messaging">messages
</a>
59 with their parent extension.
60 Content scripts can also
61 make
<a href=
"xhr">cross-site XMLHttpRequests
</a>
62 to the same sites as their parent extensions,
64 <a href=
"#host-page-communication">communicate with web pages
</a>
66 For more insight into what content scripts can and can't do,
68 <a href=
"#execution-environment">execution environment
</a>.
71 <h2 id=
"registration">Manifest
</h2>
73 <p>If your content script's code should always be injected,
75 <a href=
"manifest">extension manifest
</a>
76 using the
<code>content_scripts
</code> field,
77 as in the following example.
80 <pre data-filename=
"manifest.json">
82 "name":
"My extension",
84 <b>"content_scripts": [
86 "matches": [
"http://www.google.com/*"],
87 "css": [
"mystyles.css"],
88 "js": [
"jquery.js",
"myscript.js"]
96 If you want to inject the code only sometimes,
98 <a href=
"declare_permissions"><code>permissions
</code></a> field instead,
99 as described in
<a href=
"#pi">Programmatic injection
</a>.
102 <pre data-filename=
"manifest.json">
104 "name":
"My extension",
107 "tabs",
"http://www.google.com/*"
114 Using the
<code>content_scripts
</code> field,
115 an extension can insert multiple content scripts into a page;
116 each of these content scripts can have multiple JavaScript and CSS files.
117 Each item in the
<code>content_scripts
</code> array
118 can have the following properties:
</p>
120 <table class=
"simple">
127 <td><code>matches
</code></td>
128 <td>array of strings
</td>
129 <td><em>Required.
</em>
130 Specifies which pages this content script will be injected into.
131 See
<a href=
"match_patterns">Match Patterns
</a>
132 for more details on the syntax of these strings
133 and
<a href=
"#match-patterns-globs">Match patterns and globs
</a>
134 for information on how to exclude URLs.
</td>
136 <tr id=
"exclude_matches">
137 <td><code>exclude_matches
</code></td>
138 <td>array of strings
</td>
139 <td><em>Optional.
</em>
140 Excludes pages that this content script would otherwise be
142 See
<a href=
"match_patterns">Match Patterns
</a>
143 for more details on the syntax of these strings
144 and
<a href=
"#match-patterns-globs">Match patterns and globs
</a>
145 for information on how to exclude URLs.
</td>
147 <tr id=
"match_about_blank">
148 <td><code>match_about_blank
<code></td>
150 <td><em>Optional.
</em>
151 Whether to insert the content script on
<code>about:blank
</code> and
152 <code>about:srcdoc
</code>. Content scripts will only be injected on pages
153 when their inherit URL is matched by one of the declared patterns in the
154 <code>matches
</code> field. The inherit URL is the URL of the document that
155 created the frame or window.
157 Content scripts cannot be inserted in sandboxed frames.
159 Defaults to
<code>false
</code>.
</td>
162 <td><code>css
<code></td>
163 <td>array of strings
</td>
164 <td><em>Optional.
</em>
165 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>
168 <td><code>js
<code></td>
169 <td><nobr>array of strings
</nobr></td>
170 <td><em>Optional.
</em>
171 The list of JavaScript files to be injected into matching pages. These are injected in the order they appear in this array.
</td>
174 <td><code>run_at
<code></td>
176 <td><em>Optional.
</em>
177 Controls when the files in
<code>js
</code> are injected. Can be
"document_start",
"document_end", or
"document_idle". Defaults to
"document_idle".
181 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.
185 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.
189 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.
193 <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
194 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>
197 <td><code>all_frames
<code></td>
199 <td><em>Optional.
</em>
200 Controls whether the content script runs in all frames of the matching page, or only the top frame.
202 Defaults to
<code>false
</code>, meaning that only the top frame is matched.
</td>
204 <tr id=
"include_globs">
205 <td><code>include_globs
</code></td>
206 <td>array of string
</td>
207 <td><em>Optional.
</em>
208 Applied after
<code>matches
</code> to include only those URLs that also match this glob. Intended to emulate the
<a href=
"http://wiki.greasespot.net/Metadata_Block#.40include"><code>@include
</code></a> Greasemonkey keyword.
209 See
<a href=
"#match-patterns-globs">Match patterns and globs
</a> below for more details.
</td>
211 <tr id=
"exclude_globs">
212 <td><code>exclude_globs
</code></td>
213 <td>array of string
</td>
214 <td><em>Optional.
</em>
215 Applied after
<code>matches
</code> to exclude URLs that match this glob.
216 Intended to emulate the
<a href=
"http://wiki.greasespot.net/Metadata_Block#.40include"><code>@exclude
</code></a> Greasemonkey keyword.
217 See
<a href=
"#match-patterns-globs">Match patterns and globs
</a> below for more details.
</td>
221 <h3 id=
"match-patterns-globs">Match patterns and globs
</h3>
224 The content script will be injected into a page if its URL matches any
<code>matches
</code> pattern and any
<code>include_globs
</code> pattern, as long as the URL doesn't also match an
<code>exclude_matches
</code> or
<code>exclude_globs
</code> pattern.
226 Because the
<code>matches
</code> property is required,
<code>exclude_matches
</code>,
<code>include_globs
</code>, and
<code>exclude_globs
</code> can only be used to limit which pages will be affected.
230 For example, assume
<code>matches
</code> is
<code>[
"http://*.nytimes.com/*"]
</code>:
233 <li>If
<code>exclude_matches
</code> is
<code>[
"*://*/*business*"]
</code>, then the content script would be injected into
"http://www.nytimes.com/health" but not into
"http://www.nytimes.com/business".
</li>
234 <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>
235 <li>If
<code>exclude_globs
</code> is
<code>[
"*science*"]
</code>, then the content script would be injected into
"http://www.nytimes.com" but not into
"http://science.nytimes.com" or
"http://www.nytimes.com/science".
</li>
240 Glob properties follow a different, more flexible syntax than
<a href=
"match_patterns">match patterns
</a>. Acceptable glob strings are URLs that may contain
"wildcard" asterisks and question marks. The asterisk (*) matches any string of any length (including the empty string); the question mark (?) matches any single character.
244 For example, the glob
"http://???.example.com/foo/*" matches any of the following:
247 <li>"http://www.example.com/foo/bar"</li>
248 <li>"http://the.example.com/foo/"</li>
251 However, it does
<em>not
</em> match the following:
254 <li>"http://my.example.com/foo/bar"</li>
255 <li>"http://example.com/foo/"</li>
256 <li>"http://www.example.com/foo"</li>
259 <h2 id=
"pi">Programmatic injection
</h2>
262 Inserting code into a page programmatically is useful
263 when your JavaScript or CSS code
264 shouldn't be injected into every single page
265 that matches the pattern
—
266 for example, if you want a script to run
267 only when the user clicks a browser action's icon.
271 To insert code into a page,
272 your extension must have
273 <a href=
"xhr#requesting-permission">cross-origin permissions
</a>
275 It also must be able to use the
<code>chrome.tabs
</code> module.
276 You can get both kinds of permission
277 using the manifest file's
278 <a href=
"declare_permissions">permissions
</a> field.
282 Once you have permissions set up,
283 you can inject JavaScript into a page by calling
284 $(ref:tabs.executeScript).
286 $(ref:tabs.insertCSS).
292 <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)
293 reacts to a user click
294 by inserting JavaScript into the current tab's page
295 and executing the script.
298 <pre data-filename=
"background.html">
299 chrome.browserAction.onClicked.addListener(function(tab) {
300 chrome.tabs.executeScript({
301 code: 'document.body.style.
backgroundColor=
"red"'
305 <pre data-filename=
"manifest.json">
312 When the browser is displaying an HTTP page
313 and the user clicks this extension's browser action,
314 the extension sets the page's
<code>bgcolor
</code> property to 'red'.
316 unless the page has CSS that sets the background color,
317 is that the page turns red.
321 Usually, instead of inserting code directly (as in the previous sample),
322 you put the code in a file.
323 You inject the file's contents like this:
326 <pre>chrome.tabs.executeScript(null, {file:
"content_script.js"});
</pre>
329 <h2 id=
"execution-environment">Execution environment
</h2>
331 <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.
333 <p>For example, consider this simple page:
335 <pre data-filename=
"hello.html">
337 <button
id=
"mybutton">click me
</button
>
339 var greeting =
"hello, ";
340 var button = document.getElementById(
"mybutton");
341 button.person_name =
"Bob";
342 button.addEventListener(
"click", function() {
343 alert(greeting + button.person_name +
".");
349 <p>Now, suppose this content script was injected into hello.html:
351 <pre data-filename=
"contentscript.js">
352 var greeting =
"hola, ";
353 var button = document.getElementById(
"mybutton");
354 button.person_name =
"Roberto";
355 button.addEventListener(
"click", function() {
356 alert(greeting + button.person_name +
".");
360 <p>Now, if the button is pressed, you will see both greetings.
362 <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.
364 <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.
366 <p>It's worth noting what happens with JavaScript objects that are shared by the page and the extension - for example, the
<code>window.onload
</code> event. Each isolated world sees its own version of the object. Assigning to the object affects your independent copy of the object. For example, both the page and extension can assign to
<code>window.onload
</code>, but neither one can read the other's event handler. The event handlers are called in the order in which they were assigned.
368 <h2 id=
"host-page-communication">Communication with the embedding page
</h2>
370 <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>
371 <p>An example can be accomplished using window.postMessage (or window.webkitPostMessage for Transferable objects):
</p>
372 <pre data-filename=
"contentscript.js">
373 var port = chrome.runtime.connect();
375 window.addEventListener(
"message", function(event) {
376 // We only accept messages from ourselves
377 if (event.source != window)
380 if (event.data.type
&& (event.data.type ==
"FROM_PAGE")) {
381 console.log(
"Content script received: " + event.data.text);
382 port.postMessage(event.data.text);
386 <pre data-filename=
"http://foo.com/example.html">
387 document.getElementById(
"theButton").addEventListener(
"click",
389 window.postMessage({ type:
"FROM_PAGE", text:
"Hello from the webpage!" },
"*");
391 <p>In the above example, example.html (which is not a part of the extension) posts 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>
393 <h2 id=
"security-considerations">Security considerations
</h2>
395 <p>When writing a content script, you should be aware of two security issues.
396 First, be careful not to introduce security vulnerabilities into the web site
397 your content script is injected into. For example, if your content script
398 receives content from another web site (for example, by making an
<a
399 href=
"xhr">XMLHttpRequest
</a>),
400 be careful to filter that content for
<a
401 href=
"http://en.wikipedia.org/wiki/Cross-site_scripting">cross-site
402 scripting
</a> attacks before injecting the content into the current page.
403 For example, prefer to inject content via innerText rather than innerHTML.
404 Be especially careful when retrieving HTTP content on an HTTPS page because
405 the HTTP content might have been corrupted by a network
<a
406 href=
"http://en.wikipedia.org/wiki/Man-in-the-middle_attack">"man-in-the-middle"</a>
407 if the user is on a hostile network.
</p>
409 <p>Second, although running your content script in an isolated world provides
410 some protection from the web page, a malicious web page might still be able
411 to attack your content script if you use content from the web page
412 indiscriminately. For example, the following patterns are dangerous:
413 <pre data-filename=
"contentscript.js">
414 var data = document.getElementById(
"json-data")
415 // WARNING! Might be evaluating an evil script!
416 var parsed = eval(
"(" + data +
")")
418 <pre data-filename=
"contentscript.js">
420 // WARNING! elmt_id might be
"); ... evil script ... //"!
421 window.setTimeout(
"animate(" + elmt_id +
")",
200);
423 <p>Instead, prefer safer APIs that do not run scripts:
</p>
424 <pre data-filename=
"contentscript.js">
425 var data = document.getElementById(
"json-data")
426 // JSON.parse does not evaluate the attacker's scripts.
427 var parsed = JSON.parse(data);
429 <pre data-filename=
"contentscript.js">
431 // The closure form of setTimeout does not evaluate scripts.
432 window.setTimeout(function() {
437 <h2 id=
"extension-files">Referring to extension files
</h2>
440 Get the URL of an extension's file using
441 <code>chrome.extension.getURL()
</code>.
442 You can use the result
443 just like you would any other URL,
444 as the following code shows.
449 <em>//Code for displaying
<extensionDir
>/images/myimage.png:
</em>
450 var imgURL =
<b>chrome.extension.getURL(
"images/myimage.png")
</b>;
451 document.getElementById(
"someImage").src = imgURL;
454 <h2 id=
"examples"> Examples
</h2>
458 <a href=
"samples#search:script">examples that use content scripts
</a>.
459 A simple example of communication via messages is in the
460 <a href=
"samples#message-timer">Message Timer
</a>.
461 See
<a href=
"samples#page-redder">Page Redder
</a> and
462 <a href=
"samples#email-this-page-(by-google)">Email This Page
</a>
463 for examples of programmatic injection.
467 <h2 id=
"videos"> Videos
</h2>
470 The following videos discuss concepts that are important for content scripts.
471 The first video describes content scripts and isolated worlds.
474 <div class=
"video-container">
475 <iframe title=
"YouTube video player" width=
"640" height=
"390" src=
"//www.youtube.com/embed/laLudeUmXHM?rel=0" frameborder=
"0" allowfullscreen
></iframe>
479 The next video describes message passing,
480 featuring an example of a content script
481 sending a request to its parent extension.
484 <div class=
"video-container">
485 <iframe title=
"YouTube video player" width=
"640" height=
"390" src=
"//www.youtube.com/embed/B4M_a7xejYI?rel=0" frameborder=
"0" allowfullscreen
></iframe>