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

Experimental

Create HTML iframes, using bundled HTML, CSS and JavaScript, that can be added to a designated area of the Firefox user interface. At the moment you can only add frames to a toolbar.

Usage

This module exports the Frame constructor, which can be used to create frame components. Right now it can be used in conjunction with a Toolbar: you create a Frame, then supply it to the Toolbar's constructor, and the content is then displayed inside the toolbar.

Constructing frames

The Frame constructor takes one mandatory option, which is a url pointing to an HTML document supplied under your add-ons "data" directory.

For example, this HTML document defines a <select> element and a couple of <span> elements, and includes a CSS file to style the content and a JavaScript script to implement behavior:

<!DOCTYPE html>
<html>
  <head>
    <link href="city-info.css" rel="stylesheet"></link>
  </head>

  <body>
    <select name="city" id="city-selector"></select>
    <span id="time" class="info-element"></span>
    <span id="weather" class="info-element"></span>

    <script type="text/javascript" src="city-info.js"></script>
  </body>
</html>

If we save this document as "city-info.html" under the add-on's "data" directory, we can create a frame hosting it and add the frame to a toolbar like this:

var { Frame } = require("sdk/ui/frame");
var { Toolbar } = require("sdk/ui/toolbar");

var frame = new Frame({
  url: "./city-info.html"
});

var toolbar = Toolbar({
  name: "city-info",
  title: "City info",
  items: [frame]
});

The toolbar is positioned between the address bar and the content window. It occupies the whole width of the browser window and is 18 pixels high on a normal-resolution display or 36 pixels high on a high-resolution (HiDPI) display. This toolbar might look something like:

Scripting frames

To add scripts to frames, include them directly from the frame's HTML content, as with a normal web page:

<script type="text/javascript" src="frame.js"></script>

As usual, the path to the script is relative to the HTML file's location.

Messages logged from a frame script using the console will not appear in the terminal when you run the add-on using jpm run. However, they will appear in the Browser Console. This issue is being tracked as bug 982385.

Communicating with frames

You can exchange messages between the main add-on code and scripts loaded into the frame using an API modeled on window.postMessage(). A frame creates a separate iframe instance for each browser window. So there are three cases to consider:

  • sending messages from a frame script to the main add-on code
  • sending messages from the main add-on code to all instances of a frame, across all browser windows
  • sending messages from the main add-on code to a single instance of a frame, attached to a specific browser window

In all cases, postMessage() takes two arguments: the message itself and a targetOrigin. The targetOrigin argument can be either the URI of the document hosted by the target, or the wildcard "*". If you use the URI, then the message will only be dispatched to the window whose document matches that URI.

If you know the target URI, you should use it, as this is more secure: it prevents another window from intercepting messages that were intended for someone else.

From frame to add-on

To send a message from a frame script to the add-on, use window.parent.postMessage(). This takes two arguments, the message itself and a target origin.

If the frame script initiates the conversation, you need to specify "*" as the origin:

window.parent.postMessage("ping", "*");

If the frame script has received a message from the add-on already, it can use the origin property of the event object passed to the message hander:

// listen for messages from the add-on, and send a reply
window.addEventListener("message", function(event) {
  event.source.postMessage("pong", event.origin)
}, false);

This frame script listens to change events on the "city-selector" <select> element, and sends a message to the add-on containing the value for the newly selected element.

// city-info.js
var citySelector = window.document.getElementById("city-selector");
citySelector.addEventListener("change", cityChanged);

function cityChanged() {
  window.parent.postMessage(citySelector.value, "*");
}

To listen for these messages in the main add-on code, you can assign a listener to the frame's message event. The data property of the event is the message payload.

var { Frame } = require("sdk/ui/frame");
var { Toolbar } = require("sdk/ui/toolbar");

var frame = new Frame({
  url: "./city-info.html",
  onMessage: (e) => {
    console.log("New city: " + e.data);
  }
});

var toolbar = Toolbar({
  name: "city-info",
  title: "City info",
  items: [frame]
});

From add-on to all frames

To send a message from the add-on code to all frames, attached to all open browser windows, you can use Frame.postMessage(). You can specify the frame's url property as the targetOrigin:

frame.postMessage(message, frame.url);

This add-on listens for a frame script to send the "city changed" message above, and in response, updates all frames across all browser windows with that city's current weather (it just reads this from a dictionary, where in a real case it might ask a web service):

var { Frame } = require("sdk/ui/frame");
var { Toolbar } = require("sdk/ui/toolbar");

var weather = {
  "London" : "Rainy",
  "Toronto" : "Snowy",
  "San Francisco" : "Foggy"
}

var frame = new Frame({
  url: "./city-info.html",
  onMessage: (e) => {
    updateWeather(e.data);
  }
});

var toolbar = Toolbar({
  name: "city-info",
  title: "City info",
  items: [frame]
});

function updateWeather(location) {
  frame.postMessage(weather[location], frame.url);
}

To listen to these messages in the frame script, add a listener to the window's message event:

window.addEventListener("message", updateWeather, false);

function updateWeather(message) {
  var label = window.document.getElementById("weather");
  label.textContent = message.data;
}

From add-on to a specific frame

You can send a message from the main add-on code to the frame hosted by a particular browser window. In this way you can customize the frame for each browser window. To do this, you call postMessage() not on the Frame itself but on the source attribute of the object passed into an event listener.

For targetOrigin, you can use the origin property of the event object passed to the message listener:

var { Frame } = require("sdk/ui/frame");
var { Toolbar } = require("sdk/ui/toolbar");

var frame = new Frame({
  url: "./city-info.html",
  onMessage: function(e) {
    // message only the frame that pinged us
    e.source.postMessage("pong", e.origin);
  }
});

var toolbar = Toolbar({
  name: "ping-pong",
  title: "Ping pong",
  items: [frame]
});

This does not have to be the message event: the other events Frame can emit: attach, load and ready, also provide access to source and origin.

To receive such messages in the frame script, listen for the window's message event:

window.addEventListener("message", handlePong, false);

Sending JSON

In all cases, you can send a string as a message or a JSON object. If you send a JSON object, the SDK takes care of serializing and deserializing it for you:

// frame.js

var label = window.document.getElementById("linky");

label.addEventListener("click", function() {
  window.parent.postMessage({
    "type" : "ping",
    "reason" : "they clicked me"
  }, "*");
}, true);
// main.js

var { Frame } = require("sdk/ui/frame");

var frame = new Frame({
  url: "./frame.html"
});

frame.on("message", pong);

function pong(e) {
  if (e.data.type == "ping") {
    console.log(e.data.reason);
    e.source.postMessage("pong", event.origin);
  }
}

Globals

Constructors

Frame(options)

Creates an frame. Once created, the frame needs to be added to a toolbar for it to be visible:

var { Frame } = require("sdk/ui/frame");
var { Toolbar } = require("sdk/ui/toolbar");

var frame = new Frame({
  url: "./frame.html"
});

var toolbar = Toolbar({
  name: "my-toolbar",
  title: "My toolbar",
  items: [frame]
});
Parameters

options : object
Required options:

Name Type  
url url, string

A URL pointing to the HTML file specifying the frame's content. The file must be bundled with the add-on under its "data" directory. You can specify the URL in one of two ways:

  • as a resource:// URL pointing at a file under your add-on's "data" directory, typically constructed using self.data.url(filename)
  • as a relative path: a string in the form "./relativepath", where "relativepath" is a relative path to the file beginning in your add-on's "data" directory
var { Frame } = require("sdk/ui/frame");
var self = require("sdk/self");

var frame1 = new Frame({
  url: require("sdk/self").data.url("content1.html")
});

var frame2 = new Frame({
  url: "./content2.html"
});

Optional options:

Name Type  
name string

The frame's name. This must be unique within your add-on.

This is used to generate an ID to to keep track of the frame. If you don't supply a name, the ID is derived from the frame's URL, meaning that if you don't supply a name, you may not create two frames with the same URL.

onAttach function

Assign a listener to the frame's attach event.

onDetach function

Assign a listener to the frame's detach event.

onLoad function

Assign a listener to the frame's load event.

onReady function

Assign a listener to the frame's ready event.

onMessage function

Assign a listener to the frame's message event.

Frame

Methods

postMessage(message, targetOrigin)

Send a message to scripts loaded into the frame. This will send the message to message is all viewport documents (one per browser window) of the frame:

var { Frame } = require("sdk/ui/frame");
var { Toolbar } = require("sdk/ui/toolbar");

var frame = new Frame({
  url: "./frame.html"
});

var toolbar = Toolbar({
  name: "my-toolbar",
  title: "My toolbar",
  items: [frame]
});

frame.postMessage("ping", frame.url);

Frame scripts can receive these messages using window.addEventListener():

function ponged(message) {
  label.textContent = message.data;
}

window.addEventListener("message", ponged, false);

To send a message only to the frame instance hosted by a specific browser window call postMessage() on the source property of the object passed into any of the frame's event listeners.

Parameters

message : string
The message to send.

targetOrigin : string
Specifies the target of the message, as in window.postMessage(). In this case you should pass the frame's url property as the targetOrigin:

frame.postMessage("ping", frame.url);

on(event, listener)

Assign a listener to a frame event:

var { Frame } = require("sdk/ui/frame");

var frame = new Frame({
  url: "./frame.html"
});

frame.on("message", pong)

function pong(e) {
  if (e.data == "ping") {
    // message only the sender, and not any frames attached to other browser windows
    e.source.postMessage("pong", "*");
  }
}
Parameters

event : string
The name of the event to listen to. Frame supports the following events: attach, detach, load, ready, and message.

listener : function
The listener function. This is passed an event object which always contains a source property, which has a postMessage() function modeled after window.postMessage().  You can use this to communicate only with the specific frame instance that generated the event, and not to any frame instance attached to other browser windows.

once(event, listener)

Assign a listener to the first occurrence only of an event emitted by the frame. Frame supports the following events: attach, detach, load, ready, and message. The listener is automatically removed after the first time the event is emitted.

var { Frame } = require("sdk/ui/frame");

var frame = new Frame({
  url: "./frame.html"
});

frame.once("message", pong)

function pong(e) {
  if (e.data == "ping") {
    // message only the sender, and not any frames attached to other browser windows
    e.source.postMessage("pong", "*");
  }
}
Parameters

event : string
The name of the event to listen to. Frame supports the following events: attach, detach, load, ready, and message.

listener : function
The listener function. This is passed an event object which always contains a source property, which has a postMessage() function modeled after window.postMessage().  You can use this to communicate only with the specific frame instance that generated the event, and not to any frame instance attached to other browser windows.

removeListener(event, listener)

Removes an event listener. For example, this code is equivalent to once():

var { Frame } = require("sdk/ui/frame");

var frame = new Frame({
  url: "./frame.html"
});

frame.on("message", pong)

function pong(e) {
  if (e.data == "ping") {
    e.source.postMessage("pong", "*");
  }
  frame.removeListener("message", pong)
}
Parameters

event : string
The event the listener is listening for. Frame supports the following events: attach, detach, load, ready, and message.

listener : function
The listener to remove.

off(event, listener)

This function is an alias for removeListener().

Parameters

event : string
The event the listener is listening for. Frame supports the following events: attach, detach, load, ready, and message.

listener : function
The listener to remove.

destroy()

Destroy the frame. After calling this function, the frame will no longer appear in the UI, and accessing any of its properties or methods will throw an error.

Properties

url

URL for the content loaded into the frame. This is read-only. It's only accessible after the attach event has occurred for this frame.

Events

attach

This event is emitted whenever a new frame instance is constructed and the browser has started to load its document: for example, when the user opens a new browser window, if that window has a toolbar containing this frame. Since the event is dispatched asynchronously, the document may already be loaded by the time the event is received.

At this point, you should not try to send messages to scripts hosted in the frame, because the frame scripts may not have been loaded.

Arguments

event : This contains two properties:

  • source, which defines a postMessage() function which you can use to send messages back to this particular frame instance. But note that at this point you should not try to send messages to scripts hosted in the frame, because the frame scripts may not have been loaded.
  • origin, which you can use as the targetOrigin argument to postMessage() if you want to communicate with this particular frame instance.

detach

This event is emitted when a frame instance is unloaded: for example, when the user closes a browser window, if that window has a toolbar containing this frame. After receiving this message, you ahould not attempt to communicate with the frame scripts.

ready

This event is emitted while a frame instance is being loaded, at the point where it becomes possible to interact with the frame although sub-resources may still be in the process of loading. It's the equivalent of the point where the frame's document.readyState becomes "interactive":

var { Frame } = require("sdk/ui/frame");

var frame = new Frame({
  url: "./frame.html"
});

frame.on("ready", ping);

function ping(e) {
  // message only this frame instance
  e.source.postMessage("pong", e.origin);
}
Arguments

event : This contains two properties:

load

This event is emitted while a frame instance is completely loaded. It's the equivalent of the point where the frame's document.readyState becomes "complete":

var { Frame } = require("sdk/ui/frame");

var frame = new Frame({
  url: "./frame.html"
});

frame.on("load", ping);

function ping(e) {
  e.source.postMessage("ping", "*");
}
Arguments

event : This contains two properties:

message

Listen to this event if you want to receive messages from frame scripts that are sent using window.parent.postMessage():

// frame.js

var label = window.document.getElementById("linky");

label.addEventListener("click", function() {
  window.parent.postMessage("ping", "*");
}, true);
// main.js

var { Frame } = require("sdk/ui/frame");

var frame = new Frame({
  url: "./frame.html"
});

frame.on("message", pong);

function pong(e) {
  if (e.data == "ping") {
    e.source.postMessage("pong", e.origin);
  }
}
Arguments

event : This contains three properties:

  • source, which defines a postMessage() function which you can use to send messages back to this particular frame instance.
  • origin, which you can use as the targetOrigin argument to postMessage() if you want to communicate with this particular frame instance.
  • data, which represents the event's payload. If the payload was a JSON object, you can access it like an object:
// frame.js

var label = window.document.getElementById("linky");

label.addEventListener("click", function() {
  window.parent.postMessage({
    "type" : "ping",
    "reason" : "they clicked me"
  }, "*");
}, true);
// main.js

var { Frame } = require("sdk/ui/frame");

var frame = new Frame({
  url: "./frame.html"
});

frame.on("message", pong);

function pong(e) {
  if (e.data.type == "ping") {
    console.log(e.data.reason);
    e.source.postMessage("pong", e.origin);
  }
}

Document Tags and Contributors

 Contributors to this page: chrisdavidmills, davidi17, wbamberg, freaktechnik
 Last updated by: chrisdavidmills,