Automatically open external links in a new window

Great for Markdown powered content Posted by Joost Faassen on 2016-04-09

Markdown is great, but it doesn't allow to specify which links to open in the same window, and which ones should open in a new window or tab. Here's a set of possible solutions:

Javascript solution

While looking for a solution, I stumbled upon this Stack Overflow answer.

var links = document.links;

for (var i = 0, linksLength = links.length; i < linksLength; i++) {
   if (links[i].hostname != window.location.hostname) {
       links[i].target = '_blank';
   } 
}

or using JQuery:

$(document.links).filter(function() {
    return this.hostname != window.location.hostname;
}).attr('target', '_blank');

HTML solution

As most mardown parsers allow for plain HTML, you can simply use HTML to specify your link. For example:

<a href="http://www.google.com" target="_blank">Click here</a>

Kramdown solution

If you happen to be using Kramdown, then you can use the following syntax:

[link](url){:target="_blank"}