Working with windows in chrome code

Revision Information
  • Revision slug: Working_with_windows_in_chrome_code
  • Revision title: Working with windows in chrome code
  • Revision id: 65732
  • Created:
  • Creator: Randomandy
  • Is reviewed? Yes
  • Reviewed:
  • Reviewed by: Jay
  • Is approved? Yes
  • Is current revision? No
  • Comment /* Example 2: Interacting with the opener */ Some wording edits

Revision Source

Revision Content

This article describes working with multiple windows in Mozilla chrome code (XUL applications and Extensions). It contains tips and example code on opening new windows, finding an already opened window, and passing data between different windows.

Opening windows

To open a new window, we usually use a or window.openDialog DOM call, like this:

var win ="chrome://myextension/content/about.xul", 
                      "aboutMyExtension", "chrome,centerscreen"); 

XXX briefly explain the params and open vs openDialog; also find details about the second param of

If the window object is unavailable (for example, when opening a window from XPCOM component code), you might want to use nsIWindowWatcher interface. Its parameters are similar to, in fact implementation calls nsIWindowWatcher's methods.

var ww = Components.classes[";1"]
var win = ww.openWindow(null, "chrome://myextension/content/about.xul",
                        "aboutMyExtension", "chrome,centerscreen", null);

Window object

Note the win variable in the above section, which is assigned the return value of It can be used to access the opened window. The return value of (and similar methods) is a Window object (usually ChromeWindow), of the same type that the window variable.

Technically speaking, it implements a number of interfaces, including nsIDOMJSWindow and nsIDOMWindowInternal, but it also contains the user-defined properties for global variables and functions of the window. So, for example, to access the DOM document corresponding to the window, you can use win.document.

Note however, that the open() call returns before the window is fully loaded, so some calls, like win.document.getElementById() will fail. To overcome this difficulty, you can move the initialization code to a load handler of the window being opened or pass a callback function, as described below.

You can get a Window object from a document using document.defaultView.

Content windows

When a XUL window contains widgets such as <browser> or iframe, the documents displayed in those widgets are, naturally, separate from the document of the chrome window itself. There is a Window object for each sub-document, although there are no physical windows for those documents.

To access those sub-documents and sub-windows, use containerElement.contentDocument and containerElement.contentWindow, where containerElement is a reference to the widget. If the <browser> or <iframe> was declared with type="content-primary", you can use the content shortcut property to accesss the Window object of that primary document, for example:

alert(content.document.title); // alerts the title of the document displayed in the content-primary widget

Finding already opened windows

The window mediator XPCOM component (nsIWindowMediator interface) provides information about opened windows. Two of its methods are often used to obtain information about currently open windows: getMostRecentWindow and getEnumerator. Please refer to the MozillaZine page about nsIWindowMediator for examples and notes on using nsIWindowMediator. === Example: Opening a window only if it's not opened already === XXX TBD

Passing data between windows

When working with multiple windows, you often need to pass information from one window to another. Since different windows have separate DOM documents and global objects for scripts, you can't just use one global JavaScript variable in scripts from different windows.

There are several techniques of varying power and simplicity that can be used to share data. We'll demonstrate them from the simplest to the most complex in the next few sections.

Example 1: Passing data to window when opening it with openDialog

When you open a window using window.openDialog or nsIWindowWatcher.openWindow, you can pass an arbitrary number of arguments to that window. Arguments are simple JavaScript objects, accessible through window.arguments property in the opened window.

In this example we're using window.openDialog to open a progress dialog and specify the current status text, the maximum progress value, and the current progress.

Opener code:

                  "myProgress", "chrome,centerscreen", 
                  {status: "Reading remote data", maxProgress: 50, progress: 10} );


<?xml version="1.0"?>

<window onload="onLoad();" xmlns="">
  var gStatus, gProgressMeter;
  var maxProgress = 100;
  function onLoad() {
    gStatus = document.getElementById("status");
    gProgressMeter = document.getElementById("progressmeter");
    if("arguments" in window && window.arguments.length > 0) {
      maxProgress = window.arguments[0].maxProgress;

  function setProgress(value) {
    gProgressMeter.value = 100 * value / maxProgress;

  function setStatus(text) {
    gStatus.value = "Status: " + text + "...";
<label id="status" value="(No status)"/>
  <progressmeter id="progressmeter" mode="determined"/>
  <button label="Cancel" oncommand="close();"/>


Example 2: Interacting with the opener

Sometimes an opened window needs to interact with its opener, for example to give notice that the user has made changes in the window. This can be done using the window.opener property or via a callback function passed to the window in a way described in the previous section.

We'll add code to notify the opener when the user presses Cancel on the progress dialog in the previous example.

  • Using window.opener. The opener property returns the {{template.Anch("Window object")}} for the window that opened the current window. XXX window, window, window... someone please edit this

If we are sure that the window that opened the progress dialog declares the cancelOperation function, we can use window.opener.cancelOperation(); to notify it:

<button label="Cancel" oncommand="opener.cancelOperation(); close();"/>
  • Using a callback function. Alternatively, the opener window can pass the callback function to the progress dialog in the same way that we passed the status string in the example above:
function onCancel() {
  alert("Operation cancelled!");


                  "myProgress", "chrome,centerscreen", 

The progress dialog can then run the callback like this:

<button label="Cancel" oncommand="window.arguments[1](); close();"/>

Example 3: Using nsIWindowMediator when opener is not enough

window.opener property is very easy to use, but it's only useful when you are sure that your window is opened from few well-known places. In more complicated cases you need to use the nsIWindowMediator interface, introduced above.

An example when you might want to use nsIWindowMediator is the extension's Options window. Suppose you're developing a browser extension which consists of a browser.xul overlay and an Options window. Suppose the overlay contains a button to open extension's Options window, which needs to read some data from the browser window. As you may remember, the Firefox's Extension Manager can also be used to open your Options dialog.

This means the value of window.opener in your Options dialog is not necessarily the browser window - it may also be the Extension Manager window. You could check the location property of opener and use opener.opener in case it's the Extension Manager window, but a better way is to use nsIWindowMediator:

var wm = Components.classes[";1"]
var browserWindow = wm.getMostRecentWindow("navigator:browser");
// read values from |browserWindow|

You might be tempted to use a similar technique to apply the changes user made in the Options dialog, but a better way to do that is to use preferences observers.

Advanced data sharing

The above code is useful when you need pass data from one window to another or to a set of windows, but sometimes you just want to make a JavaScript variable shared between different windows. You could declare a variable in each window, and setter functions which will keep the "instances" of the variable in various windows in sync. But as usual there is a better way.

To declare a shared variable, we need to find a place which exists while the application is running and which is easily accessible from the code in different chrome windows. There are actually a few such places.

Using an XPCOM singleton component

The most clean and powerful way is to define your own XPCOM component (you can write one in JavaScript) and access it from any place using a getService call:

  • Pros:
    • It's the "right way".
    • You can store arbitrary JavaScript objects in the component.
    • The scope is not shared between components, so you don't have to worry about name collisions.
  • Cons:
    • You can't use the window object, it's members, like alert and open, and many other objects available from inside a window. The functionality is not lost, however, - you just have to use the XPCOM components directly instead of using convenient shortcuts. Of course, this doesn't matter if you just store data in the component.
    • Learning to create XPCOM components takes time.

There are several articles and books about creating XPCOM components online.

Storing shared data in preferences

If you just need to store a string or a number, writing a whole XPCOM component may be an unnecessary complication. You can use the preferences service XXX link in such cases.

  • Pros:
    • Quite easy to use for storing simple data.
  • Cons:
    • Can't be used to store complex data easily.
    • Abusing preferences service and not cleaning up after yourself can cause <tt>prefs.js</tt> to grow large and slow down application startup.

See MozillaZine page about preferences for detailed description of the preferences system and example code.


var prefs = Components.classes[";1"]
var branch = prefs.getBranch("extensions.myext.");
var var1 = branch.getBoolPref("var1"); // get a pref

The hidden window hack

Some extension authors use the special hidden window to store their data and code. The hidden window is similar to regular windows, but unlike any other window, it is available for the whole time the application is running, and it is not visible to user. It's used to implement the menus on Macs, so it is not necessary on Windows. There is a bug to remove it from Windows builds.

  • Pros:
    • If you're running code in the hidden window, the window object and its properties are available, unlike the component case.
    • You can store arbitrary JavaScript objects in the hidden window.
  • Cons:
    • It's a hack.
    • The hidden window may be removed from Windows builds.

You can see this technique in action in rue's SessionSaver extension.

Revert to this revision