One of the most common complaints from my boss is “how come links to external sites don’t open in a new window” and my response is usually a shrug. There are many reasons why a link may appear on a web page… A developer could forget to add the target attribute when inserting it. A content writer could be using a WYSIWYG editor that doesn’t support it. The content might be bulk loaded without proofreading for the target attribute. It’s tough to control these things (i.e. ensure that the target=”_blank” attribute is set).
I’ll ignore the religious argument over allowing users to decide how they want to open links. The person who signs my paycheck asked for this.
I wrote a Javascript function to parse out all hyperlinks on a page and set the target attribute to _blank when the href appears to be different that the current page’s host/domain. It ignores hrefs that contain or begin with “javascript:” so that a new window doesn’t open just to call a Javascript function.
This function uses Prototype, so you’ll have to download that in order to use this (or you’ll have to tweak this to not use prototype).
function externalLinksInNewWindow(){
if (!document.getElementsByTagName)
return;
var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
var thisHost = location.host;
// anchorHost is http://www.someothersite.com/somepath
var anchorHost = anchor.href;
// if anchorHost starts with http, parse it
// if it doesn't start with http (e.g. ftp://) then don't bother parsing
if (anchorHost.indexOf('http') == 0) {
// this makes anchorhost like www.someothersite.com/somepath
anchorHost = anchorHost.substring(anchorHost.indexOf('//') + 2, anchorHost.length);
// this makes anchorhost like www.someothersite.com
if (anchorHost.indexOf('/') > 0)
anchorHost = anchorHost.substring(0, anchorHost.indexOf('/'));
}
// allow for using href="javascript:myFunction()" instead of onclick="myFunction()"
if (anchorHost.indexOf('javascript:') == -1 && anchorHost != thisHost){
anchor.target = "_blank";
}
}
}
Event.observe( window, 'load', function() {
externalLinksInNewWindow();
} );