content_scripts.html revision 8ae428e0fb7feea16d79853f29447469a93bedff
1<div id="pageData-name" class="pageData">Content Scripts</div>
2<div id="pageData-showTOC" class="pageData">true</div>
3
4<p>
5Content scripts are JavaScript files that run in the context of web pages.
6By using the standard
7<a href="http://www.w3.org/TR/DOM-Level-2-HTML/">Document
8Object Model</a> (DOM),
9they can read details of the web pages the browser visits,
10or make changes to them.
11</p>
12
13<p>
14Here 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 in the DOM
21</ul>
22
23<p>
24However, content scripts have some limitations.
25They <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  <li>
41    Make <a href="xhr.html">cross-site XMLHttpRequests</a>
42  </li>
43</ul>
44
45<p>
46These limitations aren't as bad as they sound.
47Content scripts can <em>indirectly</em> use the chrome.* APIs,
48get access to extension data,
49and request extension actions
50by exchanging <a href="messaging.html">messages</a>
51with their parent extension.
52Content scripts can also
53<a href="#host-page-communication">communicate with web pages</a>
54using the shared DOM.
55For more insight into what content scripts can and can't do,
56learn 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,
63register it in the
64<a href="manifest.html">extension manifest</a>
65using the <code>content_scripts</code> field,
66as 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>
83If you want to inject the code only sometimes,
84use the
85<a href="manifest.html#permissions"><code>permissions</code></a> field instead,
86as 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>
99Using the <code>content_scripts</code> field,
100an extension can insert multiple content scripts into a page;
101each of these content scripts can have multiple JavaScript and CSS files.
102Each item in the <code>content_scripts</code> array
103can 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    Controls the 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.</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 displayed 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 injected in the order they appear in this array.</td>
130  </tr>
131  <tr>
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_start", "document_end", or "document_idle". Defaults to "document_idle".
136
137    <br><br>
138
139    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.
140
141    <br><br>
142
143    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.
144
145    <br><br>
146
147    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.
148
149    <br><br>
150
151    <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
152    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>
153  </tr>
154  <tr>
155    <td><code>all_frames<code></td>
156    <td>boolean</td>
157    <td><em>Optional.</em>
158    Controls whether the content script runs in all frames of the matching page, or only the top frame.
159    <br><br>
160    Defaults to <code>false</code>, meaning that only the top frame is matched.</td>
161  </tr>
162</table>
163
164<h2 id="pi">Programmatic injection</h2>
165
166<p>
167Inserting code into a page programmatically is useful
168when your JavaScript or CSS code
169shouldn't be injected into every single page
170that matches the pattern &mdash;
171for example, if you want a script to run
172only when the user clicks a browser action's icon.
173</p>
174
175<p>
176To insert code into a page,
177your extension must have
178<a href="xhr.html#requesting-permission">cross-origin permissions</a>
179for the page.
180It also must be able to use the <code>chrome.tabs</code> module.
181You can get both kinds of permission
182using the manifest file's
183<a href="manifest.html#permissions">permissions</a> field.
184</p>
185
186<p>
187Once you have permissions set up,
188you can inject JavaScript into a page by calling
189<a href="tabs.html#method-executeScript"><code>executeScript()</code></a>.
190To inject CSS, use
191<a href="tabs.html#method-insertCSS"><code>insertCSS()</code></a>.
192</p>
193
194<p>
195The following code
196(from the
197<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)
198reacts to a user click
199by inserting JavaScript into the current tab's page
200and executing the script.
201</p>
202
203<pre>
204<em>/* in background.html */</em>
205chrome.browserAction.onClicked.addListener(function(tab) {
206  chrome.tabs.executeScript(null,
207                           {code:"document.body.bgColor='red'"});
208});
209
210<em>/* in manifest.json */</em>
211"permissions": [
212  "tabs", "http://*/*"
213],
214</pre>
215
216<p>
217When the browser is displaying an HTTP page
218and the user clicks this extension's browser action,
219the extension sets the page's <code>bgcolor</code> property to 'red'.
220The result,
221unless the page has CSS that sets the background color,
222is that the page turns red.
223</p>
224
225<p>
226Usually, instead of inserting code directly (as in the previous sample),
227you put the code in a file.
228You inject the file's contents like this:
229</p>
230
231<pre>chrome.tabs.executeScript(null, {file: "content_script.js"});</pre>
232
233
234<h2 id="execution-environment">Execution environment</h2>
235
236<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.
237
238<p>For example, consider this simple page:
239
240<pre>hello.html
241==========
242&lt;html&gt;
243  &lt;button id="mybutton"&gt;click me&lt;/button&gt;
244  &lt;script&gt;
245    var greeting = "hello, ";
246    var button = document.getElementById("mybutton");
247    button.person_name = "Bob";
248    button.addEventListener("click", function() {
249      alert(greeting + button.person_name + ".");
250    }, false);
251  &lt;/script&gt;
252&lt;/html&gt;</pre>
253
254<p>Now, suppose this content script was injected into hello.html:
255
256<pre>contentscript.js
257================
258var greeting = "hola, ";
259var button = document.getElementById("mybutton");
260button.person_name = "Roberto";
261button.addEventListener("click", function() {
262  alert(greeting + button.person_name + ".");
263}, false);
264</pre>
265
266<p>Now, if the button is pressed, you will see both greetings.
267
268<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.
269
270<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.
271
272
273<h2 id="host-page-communication">Communication with the embedding page</h2>
274
275<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>
276
277<p>An example can be accomplished using custom DOM events and storing data in a known location. Consider: </p>
278
279<pre>http://foo.com/example.html
280===========================
281var customEvent = document.createEvent('Event');
282customEvent.initEvent('myCustomEvent', true, true);
283
284function fireCustomEvent(data) {
285  hiddenDiv = document.getElementById('myCustomEventDiv');
286  hiddenDiv.innerText = data
287  hiddenDiv.dispatchEvent(customEvent);
288}</pre>
289
290<pre>contentscript.js
291================
292var port = chrome.extension.connect();
293
294document.getElementById('myCustomEventDiv').addEventListener('myCustomEvent', function() {
295  var eventData = document.getElementById('myCustomEventDiv').innerText;
296  port.postMessage({message: "myCustomEvent", values: eventData});
297});</pre>
298
299<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>
300
301<h2 id="security-considerations">Security considerations</h2>
302
303<p>When writing a content script, you should be aware of two security issues.
304First, be careful not to introduce security vulnerabilities into the web site
305your content script is injected into.  For example, if your content script
306receives content from another web site (e.g., by <a
307href="messaging.html">asking your background page to make an
308XMLHttpRequest</a>), be careful to filter that content for <a
309href="http://en.wikipedia.org/wiki/Cross-site_scripting">cross-site
310scripting</a> attacks before injecting the content into the current page.
311For example, prefer to inject content via innerText rather than innerHTML.
312Be especially careful when retrieving HTTP content on an HTTPS page because
313the HTTP content might have been corrupted by a network <a
314href="http://en.wikipedia.org/wiki/Man-in-the-middle_attack">"man-in-the-middle"</a>
315if the user is on a hostile network.</p>
316
317<p>Second, although running your content script in an isolated world provides
318some protection from the web page, a malicious web page might still be able
319to attack your content script if you use content from the web page
320indiscriminately.  For example, the following patterns are dangerous:
321<pre>contentscript.js
322================
323var data = document.getElementById("json-data")
324// WARNING! Might be evaluating an evil script!
325var parsed = eval("(" + data + ")")
326
327contentscript.js
328================
329var elmt_id = ...
330// WARNING! elmt_id might be "); ... evil script ... //"!
331window.setTimeout("animate(" + elmt_id + ")", 200);
332</pre>
333<p>Instead, prefer safer APIs that do not run scripts:</p>
334<pre>contentscript.js
335================
336var data = document.getElementById("json-data")
337// JSON.parse does not evaluate the attacker's scripts.
338var parsed = JSON.parse(data)
339
340contentscript.js
341================
342var elmt_id = ...
343// The closure form of setTimeout does not evaluate scripts.
344window.setTimeout(function() {
345  animate(elmt_id);
346}, 200);
347</pre>
348
349<h2 id="extension-files">Referring to extension files</h2>
350
351<p>
352Get the URL of an extension's file using
353<code>chrome.extension.getURL()</code>.
354You can use the result
355just like you would any other URL,
356as the following code shows.
357</p>
358
359
360<pre>
361<em>//Code for displaying &lt;extensionDir>/images/myimage.png:</em>
362var imgURL = <b>chrome.extension.getURL("images/myimage.png")</b>;
363document.getElementById("someImage").src = imgURL;
364</pre>
365
366<h2 id="examples"> Examples </h2>
367
368<p>
369The 
370<a href="http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/docs/examples/howto/contentscript_xhr">contentscript_xhr</a> example
371shows how an extension can perform
372cross-site requests for its content script.
373You can find other simple examples of communication via messages in the
374<a href="http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/docs/examples/api/messaging/">examples/api/messaging</a>
375directory.
376</p>
377
378<p>
379See
380<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
381<a href="http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/docs/examples/extensions/email_this_page/">email_this_page</a>
382for examples of programmatic injection.
383
384</p>
385
386<p>
387For more examples and for help in viewing the source code, see
388<a href="samples.html">Samples</a>.
389</p>
390
391<h2 id="videos"> Videos </h2>
392
393<p>
394The following videos discuss concepts that are important for content scripts.
395The first video describes content scripts and isolated worlds.
396</p>
397
398<p>
399<object width="560" height="340"><param name="movie" value="http://www.youtube.com/v/laLudeUmXHM&hl=en_US&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><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"></embed></object>
400</p>
401
402<p>
403The next video describes message passing,
404featuring an example of a content script
405sending a request to its parent extension.
406</p>
407
408<p>
409<object width="560" height="340"><param name="movie" value="http://www.youtube.com/v/B4M_a7xejYI&hl=en_US&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><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"></embed></object>
410</p>
411