Visit Mozilla.org

nsIWindowMediator

From MDC

Window mediator is a Mozilla component that keeps track of open windows. It's accessed through the nsIWindowMediator interface. The two most common uses of nsIWindowMediator are:

  1. Getting the most recent / any window of a given type.
  2. Enumerating all windows of a given type.

nsIWindowMediator is defined in xpfe/appshell/public/nsIWindowMediator.idl. It is scriptable and unfrozen (hasn't changed since Mozilla 1.6).

Contents


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, "".

[edit] 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 (e.g. 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);

[edit] 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.

[edit] See also