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.

The window mediator is a Mozilla component that keeps track of open windows.
Inherits from: nsISupports Last changed in Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5)

The two most common uses of nsIWindowMediator are, enumerating all windows of a given type and getting the most recent / any window of a given type.

Implemented by: @mozilla.org/appshell/window-mediator;1 as a service:

var windowMediator = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                     .getService(Components.interfaces.nsIWindowMediator);

Method overview

void addListener(in nsIWindowMediatorListener aListener);
boolean calculateZPosition(in nsIXULWindow inWindow, in unsigned long inPosition, in nsIWidget inBelow, out unsigned long outPosition, out nsIWidget outBelow); Native code only!
nsISimpleEnumerator getEnumerator(in wstring aWindowType);
nsIDOMWindow getMostRecentWindow(in wstring aWindowType);
nsIDOMWindow getOuterWindowWithId(in unsigned long long aOuterWindowID);
nsISimpleEnumerator getXULWindowEnumerator(in wstring aWindowType);
PRUint32 getZLevel(in nsIXULWindow aWindow); Native code only!
nsISimpleEnumerator getZOrderDOMWindowEnumerator(in wstring aWindowType, in boolean aFrontToBack);
nsISimpleEnumerator getZOrderXULWindowEnumerator(in wstring aWindowType, in boolean aFrontToBack);
void registerWindow(in nsIXULWindow aWindow); Native code only!
void removeListener(in nsIWindowMediatorListener aListener);
void setZLevel(in nsIXULWindow aWindow, in PRUint32 aZLevel); Native code only!
void setZPosition(in nsIXULWindow inWindow, in unsigned long inPosition, in nsIXULWindow inBelow); Native code only!
void unregisterWindow(in nsIXULWindow aWindow); Native code only!
void updateWindowTimeStamp(in nsIXULWindow aWindow); Native code only!
void updateWindowTitle(in nsIXULWindow aWindow, in wstring inTitle ); Native code only!

Constants

Constant Value Description
zLevelTop 1 Send window to top.
zLevelBottom 2 Send window to bottom.
zLevelBelow 3 Place window below some window.

Methods

addListener()

Register a listener for window status changes.

void addListener(
  in nsIWindowMediatorListener aListener
);
Parameters
aListener
The listener to register.

Example: Of window listener object and how to register then unregister. This example below waits for listens to when a window opens, and then after that window opens it adds event listener to listen to when the window completes loading, after that it fires a function. IMPORTANT: This will attach the functionality to future opened windows, so if you copy paste this code to scratchpad, then after running this script, you need to open a new window by pressing Ctrl + N and then in the new window, selecting tabs will fire the alert.

var {Cc: classes, Ci: interfaces} = Components;

var windowListener = {
    onOpenWindow: function (aWindow) {
        // Wait for the window to finish loading
        let domWindow = aWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
        domWindow.addEventListener("load", function () {
            domWindow.removeEventListener("load", arguments.callee, false); //this removes this load function from the window
            //window has now loaded now do stuff to it
            //as example this will add a function to listen to tab select and will fire alert in that window
            if (domWindow.gBrowser && domWindow.gBrowser.tabContainer) {
                domWindow.gBrowser.tabContainer.addEventListener('TabSelect', function () {
                    domWindow.alert('tab was selected')
                }, false);
            }
        }, false);
    },
    onCloseWindow: function (aWindow) {},
    onWindowTitleChange: function (aWindow, aTitle) {}
};

//to register
Services.wm.addListener(windowListener);

//Services.wm.removeListener(windowListener); //once you want to remove this listener execute removeListener, currently its commented out so you can copy paste this code in scratchpad and see it work

Native code only!

calculateZPosition

A window wants to be moved in z-order. Calculate whether and how it should be constrained. Note this method is advisory only: it changes nothing either in WindowMediator's internal state or with the window.

Note: It compares the nsIXULWindow to nsIWidgets. A pure interface would use all nsIXULWindows. But we expect this to be called from callbacks originating in native window code. They are expected to hand us comparison values which are pulled from general storage in the native widget, and may not correspond to an nsIWidget at all. For that reason this interface requires only objects one step removed from the native window (nsIWidgets), and its implementation must be very understanding of what may be completely invalid pointers in those parameters.

boolean calculateZPosition(
  in nsIXULWindow inWindow,
  in unsigned long inPosition,
  in nsIWidget inBelow,
  out unsigned long outPosition,
  out nsIWidget outBelow
);
Parameters
inWindow
The window in question.
inPosition
Requested position one of the zLevel constants. zLevelTop send the window to the top window, zLevelBottom to the bottom. If set to zLevelBelow the window will be placed below ioBelow. The value of inBelow will be ignored for zLevelTop and zLevelBottom.)
inBelow
If inPosition is set to zLevelBelow, the window below which inWindow wants to be placed. Otherwise this variable is ignored.
outPosition
Constrained position, values like inPosition.
outBelow
The window below which inWindow should be placed, if outPosition equals zLevelBelow. Otherwise this value will be null.
Return value

PR_TRUE if the position returned is different from the position given.

getEnumerator()

Return an enumerator which iterates over all windows of type aWindowType from the oldest window to the youngest.

nsISimpleEnumerator getEnumerator(
  in wstring aWindowType
);
Parameters
aWindowType
The returned enumerator will enumerate only windows of this type. ("type" is the |windowtype| attribute of the XML <window> element.) If null, all windows will be enumerated.
Return value

An enumerator of nsIDOMWindows.

getMostRecentWindow()

This is a shortcut for simply fetching the first window in front to back order.

nsIDOMWindow getMostRecentWindow(
  in wstring aWindowType
);
Parameters
aWindowType
Return the topmost window of this type. ("type" is the |windowtype| attribute of the XML <window> element.) If null, return the topmost window of any type.
Return value

The topmost window.

Note: Starting in Gecko 8.0, the returned value is an nsIDOMWindow; previously, it was an nsIDOMWindowInternal. You may need to update your code or recompile binary components, if they use this method.

getOuterWindowWithId()

Requires Gecko 23.0 (Firefox 23.0 / Thunderbird 23.0 / SeaMonkey 2.20)

Return the outer window with the given ID, if any.

nsIDOMWindow getOuterWindowWithId(
  in unsigned long long aOuterWindowID
);

Parameters

aOuterWindowID
The id of the outer window, e.g., as obtained by nsIDOMWindowUtils.outerWindowID.

Return value

The DOM window with the given ID. If no window with the ID exists, or the window exists but it is an inner window, null is returned instead. See also: Inner and outer windows.

Note: Before Gecko 23.0, use nsIDOMWindowUtils.getOuterWindowWithId.

windowMediator = Components.classes["@mozilla.org/appshell/window-mediator;1"]
    .getService(Components.interfaces.nsIWindowMediator);

if (!windowMediator.getOuterWindowWithId) {

  windowMediator.getOuterWindowWithId = function (aOuterWindowID) {

     let win = this.getMostRecentWindow();
     let winUtil = win.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
         .getInterface(Components.interfaces.nsIDOMWindowUtils);

     return winUtil.getOuterWindowWithId(aOuterWindowID);
  }

}

getXULWindowEnumerator()

Identical to getEnumerator() except it returns nsIXULWindow instead of nsIDOMWindow.

nsISimpleEnumerator getXULWindowEnumerator(
  in wstring aWindowType
);
Parameters
aWindowType
The returned enumerator will enumerate only windows of this type; that is, the windowtype attribute of the XUL window element. If null, all windows are enumerated.
Return value

An enumerator of nsIXULWindows.

Native code only!

getZLevel

Return the window's Z level (as defined in nsIXULWindow).

PRUint32 getZLevel(
  in nsIXULWindow aWindow
);
Parameters
aWindow
The window in question.
Return value

aWindow's z level.

getZOrderDOMWindowEnumerator()

Return an enumerator which iterates over all windows of type aWindowType in their z (front-to-back) order. Note this interface makes no requirement that a window couldn't be revisited if windows are re-ordered while z-order enumerators are active.

nsISimpleEnumerator getZOrderDOMWindowEnumerator(
  in wstring aWindowType,
  in boolean aFrontToBack
);
Parameters
aWindowType
The returned enumerator will enumerate only windows of this type. ("type" is the |windowtype| attribute of the XML <window> element.) If null, all windows will be enumerated.
aFrontToBack
If true, the enumerator enumerates windows in order from front to back. Back to front if false.
Return value

An enumerator of nsIDOMWindows.

This method may not work on Linux or Mac (bug 462222) nor on OS2 (bug 370134) - please check those bugs before relying on it.  More information can be found by searching mxr for BROKEN_WM_Z_ORDER)

getZOrderXULWindowEnumerator()

Identical to getZOrderDOMWindowEnumerator() except returns an enumerator of nsIXULWindow.

nsISimpleEnumerator getZOrderXULWindowEnumerator(
  in wstring aWindowType,
  in boolean aFrontToBack
);
Parameters
aWindowType
The returned enumerator will enumerate only windows of this type. ("type" is the |windowtype| attribute of the XML <window> element.) If null, all windows will be enumerated.
aFrontToBack
If true, the enumerator enumerates windows in order from front to back. Back to front if false.
Return value

An enumerator of nsIXULWindows.

Native code only!

registerWindow

Add the window to the list of known windows. Listeners (see addListener()) will be notified through their onOpenWindow method.

void registerWindow(
  in nsIXULWindow aWindow
);
Parameters
aWindow
The window to add.

removeListener()

Unregister a listener of window status changes.

void removeListener(
  in nsIWindowMediatorListener aListener
);
Parameters
aListener
The listener to unregister.

Native code only!

setZLevel

Set the window's Z level (as defined in nsIXULWindow). The implementation will reposition the window as necessary to match its new Z level. The implementation will assume a window's Z level to be nsIXULWindow.normalZ until it has been informed of a different level.

void setZLevel(
  in nsIXULWindow aWindow,
  in PRUint32 aZLevel
);
Parameters
aWindow
The window in question.
aZLevel
The window's new Z level.

Native code only!

setZPosition

A window has been positioned behind another. Inform WindowMediator.

void setZPosition(
  in nsIXULWindow inWindow,
  in unsigned long inPosition,
  in nsIXULWindow inBelow
);
Parameters
inWindow
The window in question.
inPosition
Requested position one of the zLevel constants. zLevelTop send the window to the top window, zLevelBottom to the bottom. If set to zLevelBelow the window will be placed below ioBelow. The value of inBelow will be ignored for zLevelTop and zLevelBottom.)
inBelow
The window inWindow is behind, if zLevelBelow.

Native code only!

unregisterWindow

Remove the window from the list of known windows. Listeners (see addListener()) will be be notified through their onCloseWindow method.

void unregisterWindow(
  in nsIXULWindow aWindow
);
Parameters
aWindow
The window to remove.

Native code only!

updateWindowTimeStamp

Call this method when a window gains focus. It's a primitive means of determining the most recent window. It's no longer necessary and it really should be removed.

void updateWindowTimeStamp(
  in nsIXULWindow aWindow
);
Parameters
aWindow
The window which has gained focus.

Native code only!

updateWindowTitle

Call this method when a window's title changes. Listeners (see addListener()) will be notified through their onWindowTitleChange method.

void updateWindowTitle(
  in nsIXULWindow aWindow,
  in wstring inTitle 
);
Parameters
aWindow
The window whose title has changed.
inTitle
The window's new title.

Examples

In the examples below, type specifies the type of windows you want to search. You can specify the type of your window by putting a windowtype attribute on the top-level element, like <window> or <dialog>.

Browser windows have a window type of navigator:browser. To search all windows, regardless of their type, pass an empty string, "".

Getting most recent window

The following code is useful when you need any of the windows of given type, or to check if a window of a particular type (for example your extension's Options dialog) is already open.

getMostRecentWindow returns a ChromeWindow object, or null, if there are no windows of a given type open.

var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                   .getService(Components.interfaces.nsIWindowMediator);
var win = wm.getMostRecentWindow(type);

Changing an nsIDOMWindow to an nsIXULWindow

If you need an nsIXULWindow, you should use getXULWindowEnumerator(). However, if you are looking for the most recent nsIXULWindow, it can be helpful to get the corresponding nsIXULWindow from the nsIDOMWindow returned by getMostRecentWindow().

win.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
      .getInterface(Components.interfaces.nsIWebNavigation)
      .QueryInterface(Components.interfaces.nsIDocShellTreeItem).treeOwner
      .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
      .getInterface(Components.interfaces.nsIXULWindow) 

Enumerating windows

The following code can be used if you need to do something for each open window of a particular type. For example, you could use it in the "OK" handler of your Options dialog to apply the new settings to each open browser window.

var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                   .getService(Components.interfaces.nsIWindowMediator);
var enumerator = wm.getEnumerator(type);
while(enumerator.hasMoreElements()) {
  var win = enumerator.getNext();
  // win is [Object ChromeWindow] (just like window), do something with it
}

This code iterates over all windows of the specified type, where type you specify is the window type. If, for example, you wish to enumerate all browser windows, you would specify "navigator:browser". If you want to enumerate all windows regardless of type, specify null.

Note: In nsIWindowMediator's reference page the return type of getMostRecentWindow and the type of enumerator's elements is said to be nsIDOMWindow/nsIDOMWindowInternal. In fact, those methods usually (always?) return a ChromeWindow object, implementing both of those interfaces and a few others, when called from JavaScript code. The global window object you're probably familiar with is of ChromeWindow type.

See also

Document Tags and Contributors

 Last updated by: Sheppy,