open snippets

Opening a new window in the center of the screen with JavaScript

Tagged open, center, javascript, window, screen  Languages javascript

This JavaScript code will open a URL in a new window and center the window on the screen, instead of showing the window in a random place:

var url = 'http://google.com/';
var width  = 640;
var height = 480;
   
var left   = (screen.width / 2) - (width / 2);
var top    = (screen.height / 2) - (height / 2);
   
var xWindow = window.open(url, 'post', 'resizable=1,width=' + width + ',height=' + height + ', top=' + top + ', left=' + left);

xWindow.focus();

Opening a new tab with Firefox

Tagged tab, firefox, open  Languages javascript

Note that this only works from a Firefox extension:

function openTab(url, focus) 
  {
    var tab = getBrowser().addTab(url);

    if(focus)
    {
      getBrowser().selectedTab = tab;
    }
   
    return tab;
  }