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.

self

This article documents the self object that is available as a global in content scripts. self provides:

  • access to the options object
  • access to the port object
  • access to a mostly deprecated messaging API

For an overview of content scripts, see the main article.

Note that the self object in content scripts is completely different from the self module, which provides an API for an add-on to access its data files and ID.

self

Properties

options

Content-scripting APIs such as tab.attach(), page-mod, and page-worker let you pass read-only data to the content script as a JSON object via the contentScriptOptions option. If you do this, the data is available to the content script in the options property of self:

// main.js

const tabs = require("sdk/tabs");

tabs.open({
  url: "./page.html",
  onReady: function(tab) {
    tab.attach({
      contentScriptFile: "./content-script.js",
      contentScriptOptions: {
        a: "blah"
      }
    });
  }
});
// content-script.js

alert(self.options.a);

port

You can use port to receive messages from, and send messages to, the main add-on code. See the documentation for port.

Methods

The self object has four methods, which enable the content script to send messages to, and receive messages from, the main add-on code.

This is an older API than the API provided by port, and for most purposes the port API is a better choice. The exception is the context-menu module, which still uses postMessage.

postMessage()

Send a message from a content script to a listener in the main add-on code:

self.postMessage(contentScriptMessage);

This takes a single parameter, the message payload, which may be any JSON-serializable value.

on()

Start listening to messages from the main add-on code:

self.on("message", function(addonMessage) {
  // Handle the message
});

This takes two parameters: the name of the event, and the handler function. The handler function is passed the message payload.

once()

Exactly like on(), but stop listening after the first message is received.

removeListener()

Remove a listener to an event. This takes two parameters: the name of the event to stop listening to, and the listener function to remove.

Document Tags and Contributors

 Contributors to this page: wbamberg, erxin
 Last updated by: wbamberg,