Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Communicating With Other Scripts

This page is now obsolete, and its content has been incorporated into the main page on content scripts.

This section of the guide explains how content scripts can communicate with:

main.js

Your content scripts can communicate with your add-on's "main.js" (or any other modules you're written for your add-on) by sending it messages, using either the port.emit() API or the postMessage() API. See the articles on using postMessage() and using port for details.

Content Scripts

Content scripts loaded into the same document at the same time using the same method can interact with each other directly as well as with the web content itself. However, content scripts which have been loaded into different documents cannot interact directly with each other.  Content scripts that have been loaded into the same document by different methods, or the same method called more than once, can pass messages directly to each other using the DOM postMessage() API or a CustomEvent. Any two content scripts can communicate by using the main add-on script to manually relay messages between the content scripts.

For example:

  • If an add-on creates a single panel object and loads several content scripts into the panel at the same time, then they can interact with each other.
  • If an add-on creates two panel objects and loads a script into each one, they can't interact with each other. But, they can each communicate with the main add-on script which could be written to relay messages between them.
  • If an add-on creates a single page-mod object and loads several content scripts into the page mod, then only content scripts associated with the same page can interact with each other: if two different matching pages are loaded, content scripts attached to page A cannot interact with those attached to page B.
  • If an add-on loads two or more content scripts into the same page, or panel, using two different method (e.g. a page-mod and a context-menu) they can directly communicate by dispatching and listening for CustomEvents on DOM objects they can access (e.g. the window object). This is true as long as both context scripts have direct access to the same DOM objects.

The web content has no access to objects created by the content script, unless the content script explicitly makes them available.

For more discussion and an example please see Content Scripts: Communicating with the add-on: Content script to content script.

Page Scripts

If a page includes its own scripts using <script> tags, either embedded in the page or linked to it using the src attribute, there are a couple of ways a content script can communicate with it:

Using the DOM postMessage API

Note that before Firefox 31 code in content scripts can't use window to access postMessage() and addEventListener() and instead must use document.defaultView. See the section below on using postMessage() before Firefox 31.

You can communicate between the content script and page scripts using window.postMessage().

Messaging From Content Script To Page Script

Suppose we have a page called "listen.html" hosted at "my-domain.org", and we want to send messages from the add-on to a script embedded in that page.

In the main add-on code, we have a page-mod that attaches the content script "talk.js" to the right page:

var data = require("sdk/self").data;

var pageMod = require("sdk/page-mod");
pageMod.PageMod({
  include: "https://my-domain.org/listen.html",
  contentScriptFile: data.url("talk.js")
});

The "talk.js" content script uses window.postMessage() to send the message to the page:

// content-script (talk.js)
window.postMessage("Message from content script", "https://my-domain.org/");

The second argument may be '*' which will allow communication with any domain.

Finally, "listen.html" uses window.addEventListener() to listen for messages from the content script:

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <script>
      window.addEventListener('message', function(event) {
        window.alert(event.data);  // Message from content script
      }, false);
    </script>
  </body>
 
</html>

Messaging From Page Script To Content Script

Sending messages from the page script to the content script is just the same, but in reverse.

Here "main.js" creates a page-mod that attaches "listen.js" to the web page:

var data = require("sdk/self").data;

var pageMod = require("sdk/page-mod");
pageMod.PageMod({
  include: "https://my-domain.org/talk.html",
  contentScriptFile: data.url("listen.js")
});

The web page "talk.html" embeds a script that uses window.postMessage() to send the content script a message when the user clicks a button:

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <script>
      function sendMessage() {
        window.postMessage("Message from page script", "https://my-domain.org/");
      }
    </script>
    <button onclick="sendMessage()">Send Message</button>
  </body>
 
</html>

Finally, the content script "listen.js" uses window.addEventListener() to listen for messages from the page script:

// listen.js
window.addEventListener('message', function(event) {
  console.log(event.data);    // Message from page script
  console.log(event.origin);
}, false);

Using postMessage() before Firefox 31

If your add-on is running in a version of Firefox before Firefox 31, then your content script can't access the postMessage() or addEventListener() APIs using window, but must access them using document.defaultView instead. So the content scripts in the above examples need to be rewritten like this:

// content-script.js
document.defaultView.postMessage("Message from content script", "https://my-domain.org/");
// content-script.js
document.defaultView.addEventListener('message', function(event) {
  console.log(event.data);    // Message from page script
  console.log(event.origin);
}, false);

Using Custom DOM Events

As an alternative to using postMessage() you can use custom DOM events to communicate between page scripts and content scripts.

Messaging From Content Script To Page Script

From Firefox 30 onwards, the execution environment for content scripts has changed, so content scripts can't directly share objects with page scripts. This affects the use of custom events to send messages from content scripts to page scripts.

Before Firefox 30

Here's an example showing how to use custom DOM events to send a message from a content script to a page script, before Firefox 30.

First, "main.js" will create a page-mod that will attach "content-script.js" to the target web page, and will then load the target web page:

var tabs = require("sdk/tabs");
var mod = require("sdk/page-mod");
var self = require("sdk/self");

var pageUrl = self.data.url("page.html")

var pageMod = mod.PageMod({
  include: pageUrl,
  contentScriptFile: self.data.url("content-script.js"),
  contentScriptWhen: "ready"
})

tabs.open(pageUrl);

The target web page "page.html" includes a button and a page script:

<html>
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    <input id="message" type="button" value="Send a message"/>
    <script type="text/javascript" src="page-script.js"></script>
  </body>
</html>

The content script "content-script.js" adds an event listener to the button, that sends a custom event containing a message:

var messenger = document.getElementById("message");
messenger.addEventListener("click", sendCustomEvent, false);

function sendCustomEvent() {
  var greeting = {"greeting" : "hello world"};
  var event = document.createEvent('CustomEvent');
  event.initCustomEvent("addon-message", true, true, greeting);
  document.documentElement.dispatchEvent(event);
}

Finally, the page script "page-script.js" listens for the message and logs the greeting to the Web Console:

window.addEventListener("addon-message", function(event) {
  console.log(event.detail.greeting);
}, false);

After Firefox 30: clone the message object

This technique depends on being able to share the message payload between the content script scope and the page script scope. From Firefox 30 this sharing requires an extra step: the content script needs to explicitly clone the message payload into the page script's scope using the global cloneInto() function:

var messenger = document.getElementById("message");
messenger.addEventListener("click", sendCustomEvent, false);

function sendCustomEvent() {
  var greeting = {"greeting" : "hello world"};
  var cloned = cloneInto(greeting, document.defaultView);
  var event = document.createEvent('CustomEvent');
  event.initCustomEvent("addon-message", true, true, cloned);
  document.documentElement.dispatchEvent(event);
}

Messaging From Page Script to Content Script

Sending messages using custom DOM events from the page script to the content script is just the same, but in reverse. Also, there's no need to clone the message when using custom DOM events in this direction.

In this example, "main.js" creates a page-mod to target the page we are interested in:

var data = require("sdk/self").data;

var pageMod = require("sdk/page-mod");
pageMod.PageMod({
  include: "https://my-domain.org/talk.html",
  contentScriptFile: data.url("listen.js")
});

The web page "talk.html" creates and dispatches a custom DOM event, using initCustomEvent()'s detail parameter to supply the payload:

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <script>
      function sendMessage() {
        var event = document.createEvent('CustomEvent');
        event.initCustomEvent("addon-message", true, true, { hello: 'world' });
        document.documentElement.dispatchEvent(event);
      }
    </script>
    <button onclick="sendMessage()">Send Message</button>
  </body>
</html>

Finally, the content script "listen.js" listens for the new event and retrieves the payload from its detail attribute:

window.addEventListener("addon-message", function(event) {
  console.log(JSON.stringify(event.detail));
}, false);

Document Tags and Contributors

 Contributors to this page: Makyen, Jaja, wbamberg, michaelkonecny, jsantell, evold
 Last updated by: Makyen,