• Skip to main content
  • Select language
  • Skip to search
MDN Web Docs
  • Technologies
    • HTML
    • CSS
    • JavaScript
    • Graphics
    • HTTP
    • APIs / DOM
    • WebExtensions
    • MathML
  • References & Guides
    • Learn web development
    • Tutorials
    • References
    • Developer Guides
    • Accessibility
    • Game development
    • ...more docs
Add-ons
  1. MDN
  2. Mozilla
  3. Add-ons
  4. Add-on SDK
  5. Low-Level APIs
  6. ui/frame

ui/frame

In This Article
  1. Usage
    1. Constructing frames
    2. Scripting frames
    3. Communicating with frames
      1. From frame to add-on
      2. From add-on to all frames
      3. From add-on to a specific frame
      4. Sending JSON
  2. Globals
    1. Constructors
      1. Frame(options)
  3. Frame
    1. Methods
      1. postMessage(message, targetOrigin)
      2. on(event, listener)
      3. once(event, listener)
      4. removeListener(event, listener)
      5. off(event, listener)
      6. destroy()
    2. Properties
      1. url
    3. Events
      1. attach
      2. detach
      3. ready
      4. load
      5. message

Add-ons using the techniques described in this document are considered a legacy technology in Firefox. Don't use these techniques to develop new add-ons. Use WebExtensions instead. If you maintain an add-on which uses the techniques described here, consider migrating it to use WebExtensions.

From Firefox 53 onwards, no new legacy add-ons will be accepted on addons.mozilla.org (AMO).

From Firefox 57 onwards, WebExtensions will be the only supported extension type, and Firefox will not load other types.

Even before Firefox 57, changes coming up in the Firefox platform will break many legacy extensions. These changes include multiprocess Firefox (e10s), sandboxing, and multiple content processes. Legacy extensions that are affected by these changes should migrate to WebExtensions if they can. See the "Compatibility Milestones" document for more.

A wiki page containing resources, migration paths, office hours, and more, is available to help developers transition to the new technologies.

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:

  • 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.

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:

  • 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.

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: wbamberg, chrisdavidmills, davidi17, freaktechnik
 Last updated by: wbamberg, Dec 1, 2016, 10:36:38 AM
See also
  1. WebExtensions
  2. Getting started
    1. What are WebExtensions?
    2. Your first WebExtension
    3. Your second WebExtension
    4. Anatomy of a WebExtension
    5. Example WebExtensions
  3. How to
    1. Intercept HTTP requests
    2. Modify a web page
    3. Add a button to the toolbar
    4. Implement a settings page
  4. Concepts
    1. Using the JavaScript APIs
    2. User interface components
    3. Content scripts
    4. Match patterns
    5. Internationalization
    6. Content Security Policy
    7. Native messaging
  5. Porting
    1. Porting a Google Chrome extension
    2. Porting a legacy Firefox add-on
    3. Embedded WebExtensions
    4. Comparison with the Add-on SDK
    5. Comparison with XUL/XPCOM extensions
    6. Chrome incompatibilities
  6. Firefox workflow
    1. Temporary Installation in Firefox
    2. Debugging
    3. Getting started with web-ext
    4. web-ext command reference
    5. WebExtensions and the Add-on ID
    6. Publishing your WebExtension
  7. JavaScript APIs
    1. Browser support for JavaScript APIs
    2. alarms
    3. bookmarks
    4. browserAction
    5. browsingData
    6. commands
    7. contextMenus
    8. contextualIdentities
    9. cookies
    10. downloads
    11. events
    12. extension
    13. extensionTypes
    14. history
    15. i18n
    16. identity
    17. idle
    18. management
    19. notifications
    20. omnibox
    21. pageAction
    22. runtime
    23. sessions
    24. sidebarAction
    25. storage
    26. tabs
    27. topSites
    28. webNavigation
    29. webRequest
    30. windows
  8. Manifest keys
    1. applications
    2. author
    3. background
    4. browser_action
    5. chrome_url_overrides
    6. commands
    7. content_scripts
    8. content_security_policy
    9. default_locale
    10. description
    11. developer
    12. homepage_url
    13. icons
    14. manifest_version
    15. name
    16. omnibox
    17. options_ui
    18. page_action
    19. permissions
    20. short_name
    21. sidebar_action
    22. version
    23. web_accessible_resources
  9. Add-on SDK
  10. Getting started
    1. Installation
    2. Getting started
    3. Troubleshooting
  11. High-Level APIs
    1. addon-page
    2. base64
    3. clipboard
    4. context-menu
    5. hotkeys
    6. indexed-db
    7. l10n
    8. notifications
    9. page-mod
    10. page-worker
    11. panel
    12. passwords
    13. private-browsing
    14. querystring
    15. request
    16. selection
    17. self
    18. simple-prefs
    19. simple-storage
    20. system
    21. tabs
    22. timers
    23. ui
    24. url
    25. webextension
    26. widget
    27. windows
  12. Low-Level APIs
    1. /loader
    2. chrome
    3. console/plain-text
    4. console/traceback
    5. content/content
    6. content/loader
    7. content/mod
    8. content/symbiont
    9. content/worker
    10. core/heritage
    11. core/namespace
    12. core/promise
    13. dev/panel
    14. event/core
    15. event/target
    16. frame/hidden-frame
    17. frame/utils
    18. fs/path
    19. io/byte-streams
    20. io/file
    21. io/text-streams
    22. lang/functional
    23. lang/type
    24. loader/cuddlefish
    25. loader/sandbox
    26. net/url
    27. net/xhr
    28. places/bookmarks
    29. places/favicon
    30. places/history
    31. platform/xpcom
    32. preferences/event-target
    33. preferences/service
    34. remote/child
    35. remote/parent
    36. stylesheet/style
    37. stylesheet/utils
    38. system/child_process
    39. system/environment
    40. system/events
    41. system/runtime
    42. system/unload
    43. system/xul-app
    44. tabs/utils
    45. test/assert
    46. test/harness
    47. test/httpd
    48. test/runner
    49. test/utils
    50. ui/button/action
    51. ui/button/toggle
    52. ui/frame
    53. ui/id
    54. ui/sidebar
    55. ui/toolbar
    56. util/array
    57. util/collection
    58. util/deprecate
    59. util/list
    60. util/match-pattern
    61. util/object
    62. util/uuid
    63. window/utils
  13. Firefox for Android
  14. Getting started
    1. Walkthrough
    2. Debugging
    3. Code snippets
  15. APIs
    1. Accounts.jsm
    2. BrowserApp
    3. HelperApps.jsm
    4. Home.jsm
    5. HomeProvider.jsm
    6. JavaAddonManager.jsm
    7. NativeWindow
    8. Notifications.jsm
    9. PageActions.jsm
    10. Prompt.jsm
    11. RuntimePermissions.jsm
    12. Snackbars.jsm
    13. Sound.jsm
    14. Tab
  16. Legacy
  17. Restartless extensions
    1. Overview
  18. Overlay extensions
    1. Overview
  19. Themes
  20. Lightweight themes
    1. Overview
  21. Complete themes
    1. Overview
  22. Publishing add-ons
  23. Guides
    1. Signing and distribution overview
    2. Submit an add-on
    3. Review policies
    4. Developer agreement
    5. Featured add-ons
    6. Contact addons.mozilla.org
  24. Community and support
  25. Channels
    1. Add-ons blog
    2. Add-on forums
    3. Stack Overflow
    4. Development newsgroup
    5. IRC Channel