Contents
Content Scripts are JavaScript files that run in the context of web pages. By using the standard Document Object Model (DOM), they can read details of the web pages the browser visits, or make changes to them.
Some examples of things that content scripts can do include:
- Find unlinked URLs in web pages and convert them into hyperlinks
- Increase the font size to make text more legible
- Find and process microformat data in the DOM
Manifest
Content scripts are registered in an extension's manifest.json file, like so:
{
"name": "My First Extension",
"version": "1.0",
"description": "The first extension that I made.",
"content_scripts": [
{
"matches": ["http://www.google.com/*"],
"css": ["mystyles.css"],
"js": ["jquery.js", "myscript.js"]
}
]
}
An extension can contain any number of content scripts, and a content script can consist of any number of JavaScript or CSS files. The value of the matches
property controls when the content script will run.
Each content script registered in the manifest can specify the following properties:
Name | Type | Description |
---|---|---|
matches | array of strings | Required. Controls the pages this content script will be injected into. See Match Patterns for more details on the syntax of these strings. |
js | Optional. The list of JavaScript files to be injected into matching pages. These are injected in the order they appear in this array. | |
css | array of strings | Optional. 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. |
run_at | string | Optional. Controls when the files in js are injected. Can be "document_start" or "document_end" . Defaults to "document_end" . In the case of "document_start" , the files are injected after any files from "css" , but before any other DOM is constructed or any other script is run. In the case of "document_end" , the files are injected after the DOM is complete, but before subresources like images and frames have necessarily loaded. |
Execution environment
Content scripts execute in a special environment called an isolated world. 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.
For example, consider this simple page:
hello.html =========== <html> <button id="button">click me</button> <script> var greeting = "hello!"; function sayGreeting() { alert(greeting); } document.getElementById("button").onclick = sayGreeting; </script> </html>
Now, suppose this content script was injected into hello.html:
contentscript.js ================== console.log(greeting); // undefined console.log(sayGreeting); // undefined console.log(document.getElementById("button").onclick); // still undefined document.getElementById("button").onclick = function() { alert("hola!"); }
Now, if the button is pressed, you will see both greetings.
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.
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.
Messaging
Content scripts can communicate with their parent extension using message passing. A message channel can be opened by either the content script or an extension page. Each side of the channel has a Port object which can be used to send messages to the other side. The messages can contain any valid JSON object (null, boolean, number, string, array, or object).
The content script opens a channel to the extension using the chrome.extension.connect() method. The parent extension can also open a channel to a content script in a given tab by calling chrome.tabs.connect(tabId). In either case, the onConnect event is fired in the targeted page(s), and a connection is established.
When a channel is opened from a content script to an extension, the event is fired in all views in the extension. Any view can receive the event.
For example, suppose you want to write a simple login manager. You want a toolstrip button that lights up when a content script detects a "login" element in a page, and fills in the login info when you press the button.
Your content script would look like this:
contentscript.js ================ var e = document.getElementById("login"); // Create a short-lived named channel to the extension and send a single // message through it. var port = chrome.extension.connect({name: "notifyChannel"}); port.postMessage({found: (e != undefined)}); // Also listen for new channels from the extension for when the button is // pressed. chrome.extension.onConnect.addListener(function(port, name) { console.assert(name == "buttonClickedChannel"); port.onMessage.addListener(function(msg) { if (msg.buttonClicked) { e.value = msg.passwordValue; } }); });
with a toolstrip that looks like:
toolstrip.html ============== <div class="toolstrip-button" id="btn" onclick="onClick()"> Fill Password </div> <script> // Listen for notifications from the content script. chrome.extension.onConnect.addListener(function(port, name) { console.assert(name == "notifyChannel"); port.onMessage.addListener(function(msg) { // Color our button based on whether a login element was found. var color = msg.found ? "blue" : "grey"; document.getElementById("btn").style.backgroundColor = color; }); }); function onClick() { // Send our password to the current tab when clicked. chrome.tabs.getSelected(null, function(tab) { var port = chrome.tabs.connect(tab.id, {name: "buttonClickedChannel"}); port.postMessage({buttonClicked: true}); }); } </script>
Communication with the embedding page
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.
An example can be accomplished using custom DOM events and storing data in a known location. Consider:
http://foo.com/example.html ================================ var customEvent = document.createEvent('Event'); customEvent.initEvent('myCustomEvent', true, true); function fireCustomEvent(data) { hidenDiv = document.getElementById('myCustomEventDiv'); hidenDiv.innerHTML = data hidenDiv.dispatchEvent(customEvent); }
contentscript.js ===================== var port = chrome.extension.connect(); document.getElementById('myCustomEventDiv').addEventListener('myCustomEvent', function() { var eventData = document.getElementById('myCustomEventDiv').innerHTML; port.postMessage({message: "myCustomEvent", values: eventData}); });
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.
Referring to extension files
Get the URL of an extension's file using
chrome.extension.getURL()
.
You can use the result
just like you would any other URL,
as the following code shows.
//Code for displaying <extensionDir>/images/myimage.png: var imgURL = chrome.extension.getURL("images/myimage.png"); document.getElementById("someImage").src = imgURL;