Dive Into Greasemonkey

Teaching an old web new tricks

5.4. Case study: Offsite Blank

Forcing offsite links to open in a new window

Offsite Blank is a user script that I wrote after someone posted a request to the Greasemonkey script repository. I personally like to open links in a new tab in the current window, but other people prefer to open a separate window for each site. Offsite Blank lets you do this automatically, by forcing offsite links to open in a new window.

Example: offsiteblank.user.js

// ==UserScript==
// @name          Offsite Blank
// @namespace     http://diveintogreasemonkey.org/download/
// @description   force offsite links to open in a new window
// @include       http://*
// @include       https://*
// ==/UserScript==

var a, thisdomain, links;
thisdomain = window.location.host;
links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
    a = links[i];
    if (a.host && a.host != thisdomain) {
        a.target = "_blank";
    }
}

First, I declare that this user script should run on every web page (but not, for example, on HTML documents stored on your local machine that you open from the FileOpen menu).

// @include       http://*
// @include       https://*

The code breaks down into four steps:

  1. Get the domain of the current page.
  2. Get a list of all the links on the page.
  3. Compare the domain of each link to the domain of the page.
  4. If the domains don't match, set the target of the link so it opens in a new window.

Getting the domain of the current page is easy. See Getting the current domain name for more information.

thisdomain = window.location.host;

Getting a list of all the links on the page is equally easy, although I should note that I am ignoring my own advice and simply using document.getElementsByTagName('a') instead of doing an XPath query. To-may-to, to-mah-to...

links = document.getElementsByTagName('a');

Next I loop through all the links (well, all the <a> elements, some of which might be links) and check whether the domain of the link matches the domain of the current page. Because some links might point to non-HTTP URLs (for example, they could point to a local file, or to an FTP server), I need to check whether a.host exists, then check whether it's equal to the current domain.

for (var i = 0; i < links.length; i++) {
    a = links[i];
    if (a.host && a.host != thisdomain) {
        ...
    }

If I find a link that has a domain but isn't the same as the current domain, I simply set its target attribute to "_blank" to force the link to open in a new window.

        a.target = "_blank";
← Case study: Ain't It Readable
Case study: Dumb Quotes →