Hack #14. Force Offsite Links to Open in a New Window

Keep your browser organized by automatically opening each site in its own window.

I originally wrote this user script 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 some 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.

The Code

This user script runs on remote web sites (but not, for example, on HTML documents stored on your local machine that you open from the File Open menu). Since search engines exist to provide links to other pages, and I find it annoying for search result links to open new links, I've excluded Google and Yahoo! by default.

The code itself 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 attribute of the link so that it opens in a new window.

Save the following user script as offsiteblank.user.js:

	// ==UserScript==
	// @name		  Offsite Blank
	// @namespace	  http://diveintomark.org/projects/greasemonkey/
	// @description	  force offsite links to open in a new window
	// @include		  http*://*
	// @exclude       http://*.google.tld/* // @exclude http://*.yahoo.tld/* // ==/UserScript== var sCurrentHost = location.host; var arLinks = document.links; for (var i = arLinks.length - 1; i >= ...

Get Greasemonkey Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.