Tip:
Highlight text to annotate it
X
Hi, I'm Matt, and I'm a software engineer working on Google Chrome.
I'm going to tell you about extension message passing, which allows the different components
of your extension to communicate with each other.
Content scripts run in a separate JavaScript environment from the rest of your extension,
to allow them direct access to a web page's DOM.
For security reasons, this JavaScript environment is unprivileged, just like the web page it
affects.
That means that if you want to access some extension API from your content script, you
need a way to communicate between your content script and the privileged part of your extension.
This is where message passing comes in.
Message passing allows the different pieces of your extension to communicate.
Usually you'll want to send messages between a content script and a background page, but
message passing works from any page to any other page or pages in your extension.
You can even send a message to another extension as long as you know that extension's unique
ID.
Let's walk through a simple example to see how message passing works.
Let's say we want to write an RSS feed reading extension.
We want a button to appear in the URL bar whenever the current page has an RSS feed
available.
To start, we write a content script that examines the page to detect an RSS feed.
Since the content script doesn't have access to modify the browser UI, it needs to ask
the background page to do that.
The call to sendRequest passes the list of feeds found by the content script up to the
background page.
Our background page looks like this:
The first line adds a listener to the onRequest event, which is fired when our content script
calls sendRequest.
In our listener, we check if there were any feeds found, and if so, display the page action
for that page.
That's how you send a single request to your extension from a content script.
There is a slightly more involved API if you need to have a longer lived conversation with
multiple back-and-forth messages.
To find out more details, visit the extension documentation page at code.google.com/chrome/extensions
http://code.google.com/chrome/extensions/index.html