Visit Mozilla.org

Code snippets:Windows

From MDC

Contents

[edit] Opening new browser windows

To open a new browser window, you can simply use window.open(). However, window.open() returns a Window object for content, not for the browser window itself, so you should get the chrome Window first. The simplest way to do that is to use nsIWindowMediator.

[edit] Example

window.open();
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                   .getService(Components.interfaces.nsIWindowMediator);
var newWindow = wm.getMostRecentWindow("navigator:browser");
var b = newWindow.getBrowser();
// why did we do this? we never do anything with |b|

[edit] Draggable windows

To make a window draggable by clicking on the window's contents, you can use the mousedown and mousemove events. The following code does not care which element is clicked on, simply responding to all mousedown events equally. You could improve this code by checking the event.target element and only setting the startPos if the element matches some criteria.

[edit] Example

var startPos=0;
var mouseDown = function(event) {
    startPos = [ event.clientX, event.clientY];
}
var mouseMove = function(event) {
   if (startPos != 0) {
       var newX = event.screenX-startPos[0];
       var newY = event.screenY-startPos[1];
       window.moveTo(newX,newY);
   }
}
var mouseUp = function(event) {
   startPos=0;
}

window.addEventListener("mousedown",mouseDown, false);
window.addEventListener("mouseup",mouseUp, false);
window.addEventListener("mousemove",mouseMove, false);

[edit] XUL Titlebar Element

XUL Applications can take advantage of the Titlebar element to achieve a similar result without extra JavaScript code.

[edit] Re-using and focusing named windows

This section is incorrect and needs to be rewritten. See nsIWindowMediator for the correct docs.

While specifying the name parameter to window.open or window.openDialog will prevent multiple windows of that name from opening, each call will actually re-initialize the window and thus lose whatever state the user has put it in. Additionally, if the window is in the background, it may not be brought to the front. This code will check for a window of the provided name. If it finds one, it focuses it. If it doesn't, it opens one.

var windowName = "yourWindowName";
var windowsMediator = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
var win = windowsMediator.getMostRecentWindow(windowName);
if (win)
  win.focus();
else
  window.open("chrome://to/your/window.xul", windowName, "features");

[edit] Other resources