The Chromium Projects

Except as otherwise noted, the content of this page is licensed under a Creative Commons Attribution 2.5 license, and examples are licensed under the BSD License.

The Chromium OS designs and code are preliminary. Expect them to evolve.
For Developers‎ > ‎Design Documents‎ > ‎Extensions‎ > ‎

Content Scripts

This page is obsolete. Please see the new version at:

http://code.google.com/chrome/extensions/content_scripts.html

Overview

Content Scripts are JavaScript files that run in the context of web pages that the browser loads. Content scripts are similar to the Greasemonkey extension for Firefox. Content scripts allow extensions to interact with web pages because content scripts and extensions can communicate.

Status

Implemented, and ready to roll.

Details

To add a content script, register it in the manifest like this:

{
  "name": "My First Extension",
  "version": "1.0",
  "description": "The first extension that I made.",
  "content_scripts": [
    {
      "matches": ["http://www.google.com/*"],
      "js": ["foo.js"]
    }
  ]
}

Then create a file called foo.js in your extension with this code:

document.images[0].src = "http://bit.ly/1293Af";
document.images[0].style.height = "auto";

Restart Chrome and navigate to http://www.google.com. You should see your image instead of the Google logo.

Manifest Syntax

The content_scripts item in the manifest is an array of objects, each of which has the following keys:
  • matches: An array of match patterns describing which pages the content script should run on.  If any of the match patterns matches a URL, the content script is run.
  • js: Optional. An array of paths to JavaScript files to run. The files are run in the order they are listed in the array.
  • css: Optional. An array of paths to CSS files to run. The files are run in the order they are listed in the array. 
  • run_at: Optional. Can be "document_start" or "document_end". Defaults to "document_end".

Execution Environment

Each content script executes in its own distinct global scope, separate from the global scope of the web page JavaScript, and from every other content script. This means that if a web page defines a global variable "foo", it won't conflict with a content script's global variable "foo". Also, each content script has its own copy of the built-in JavaScript global objects "String", "Array", "Object", etc.


Content Script Messaging

Content scripts can communicate with their parent extension using message passing. The content script opens a channei to the extension using the chrome.extension.connect() method and then send messages back and forth to it. The messages can contain any valid JSON object (null, boolean, number, string, array, or object).

The parent extension can also open a channel to a content script in a given tab by calling chrome.tabs.connect(tabId).

When a channel is opened, the onConnect event is dispatched to the receiving end, which is given a message port object that can be used to communicate with the content. Any listeners that have attached to the onConnect event get called. If the channel was opened from a tab or content script, the port holds a tab object identifying the tab that opened the connection. Note that this object contains the state of the tab as of the time of the connection, so most data can become stale.

For example:

// In a content script
var port = chrome.extension.connect('greetings');
port.onMessage.addListener(function(data) {
  console.log("The extension said: " + data.message + " with values: " + data.values);
});
port.postMessage({message: "Hello!", values: [1,2,3]});

// In an extension
chrome.extension.onConnect.addListener(function(port) {
  // Only accept connections with a port.name we expect.
  if (port.name != 'greetings')
    return; 
  port.onMessage.addListener(function(data) {
    console.log("The content script said: " + data.message + " with values: " + data.values);
  });
  port.postMessage({message: "Greetings, tab " + port.tab.id, values: [true,false,null]});
});

Note: Because content scripts are not currently sandboxed from web page JavaScript, web pages can also send messages to and receive messages from extensions. This will be fixed before the launch of the Chrome extensions API.

APIs

Content scripts have a few special APIs available to them.

chrome.extension
  // One end of a connection to the extension process.
  class Port {
    // Fired when the other side of the port sends a message on the channel. |data| is a
    // JSON-compatible value.
    Event onMessage(Object data)

    // Fired when the other side of the port has disconnected (eg because the window or tab closed)
    Event onDisconnect()

    // Send a message to the other side of the port. |data| is any JSON-compatible value.
    void postMessage(Object data)

    // Forcibly closes the channel.  This will notify the other side of the port via the onDisconnect event.
    void disconnect();

    // If the port is a receiving port and the sender opened the channel with a name, this property
    // contains that name.
    String name;
  }

  // Gets the fully-qualified URL to a path inside the extension. This can be used,
  // for example, to add images from an extension to web pages.
  String getURL(String path)

  // Open a channel to the content script's extension to communicate with it.
  // The chrome.extension.onConnect event is fired to all components of this extension each time
  // this method is called.
  // The channel can optionally be named. This name will be sent along with the onConnect event.
  Port connect([String channelName])

  // Fired when the extension opens a channel to a tab via the chrome.tabs.connect(tabId) call.
  // If a channelName was provided, it is accessible via port.name.
  Event onConnect(Object port)