Almost all interesting add-ons will need to interact with web content or the browser's user interface. For example, they may need to access and modify the content of web pages or be notified when the user clicks a link.
The SDK provides several core modules to support this:
Create a dialog that can host web content.
Retrieve a page and access its content, without displaying it to the user.
Execute scripts in the context of selected web pages.
Host an add-on's user interface, including web content.
Add items to the browser's context menu.
Firefox is moving towards a model in which it uses separate processes to display the UI, handle web content, and execute add-ons. The main add-on code will run in the add-on process and will not have direct access to any web content.
This means that an add-on which needs to interact with web content needs to be structured in two parts:
- the main script runs in the add-on process
- any code that needs to interact with web content is loaded into the web content process as a separate script. These separate scripts are called content scripts.
A single add-on may use multiple content scripts, and content scripts loaded into the same context can interact directly with each other as well as with the web content itself. See the chapter on content script access.
The add-on script and content script can't directly access each other's state. Instead, you can define your own events which each side can emit, and the other side can register listeners to handle them. The interfaces are similar to the event-handling interfaces described in the Working with Events guide.
The diagram below shows an overview of the main components and their relationships. The gray fill represents code written by the add-on developer.
This might sound complicated but it doesn't need to be. The following add-on
uses the page-mod module to replace the
content of any web page in the
.co.uk domain by executing a content script
in the context of that page:
var pageMod = require("page-mod");
contentScript: 'document.body.innerHTML = ' +
'"<h1>this page has been eaten</h1>";'
In this example the content script is supplied directly to the page mod via
contentScript option in its constructor, and does not need to be
maintained as a separate file at all.
The next few chapters explain content scripts in detail:
- Loading Content Scripts: how to attach content scripts to web pages, and how to control the point at which they are executed
- Content Script Access: detail about the access content scripts get to the DOM, to other content scripts, and to scripts loaded by the page itself
- Communicating Using
port: how to communicate between your add-on and its content scripts using the
- Communicating using
postMessage(): how to communicate between your add-on and its content scripts using the
- Example: a simple example add-on using content scripts