How to automatically add target="_blank" to external links only?

I've been using the following for awhile. Can't remember where I found it originally:

$.expr[':'].external = function(obj){
    return !obj.href.match(/^mailto\:/)
           && (obj.hostname != location.hostname)
           && !obj.href.match(/^javascript\:/)
           && !obj.href.match(/^$/)
};

That adds an :external jQuery selector, so then you can just do:

$('a:external').attr('target', '_blank');

The nice part about using the custom selector, is that if you need to modify what contitutes an "external" link, you can change it in one place and not worry about the rest of your code. For instance in my organization, we have certain subdomains that aren't "external", but that we still want to open in new windows.


Try something like

for (var links = document.links, i = 0, a; a = links[i]; i++) {
        if (a.host !== location.host) {
                a.target = '_blank';
        }
}

Don't forget to run the script by the time all links exist in the document tree - in window.onload event.


You could do something like this:

$(document.body).on('mouseover', 'a[target!=_blank]:not(.local)', function (evt) {
    var a = $(this);
    var href = a.attr('href');
    var domain = href.match(/^https?:\/\/([^:\/]+)/);
    if (domain && domain[1] && domain[1] !== "yourdomain.com") {
        a.attr('target', '_blank');
    } else {
        a.addClass('local');
    }
});

This will process each link as you click it, and shouldn't process each link more than once. If it needs to be external, the target will be set to _blank and it should open in a new window. Here's a working jsfiddle.

Update: My method of determining if the link stays on-site or not is quite crude. The method in this answer is more thorough. I would probably replace my simple regex match with that test instead.