theraneman
theraneman

Reputation: 1630

How to open only external links in a new browser window via JavaScript?

I know this is a common requirement and there are lots of answers out in the wild. I would really appreciate if someone can provide a correct script which opens only external links from an HTML file in a new window.

Upvotes: 0

Views: 565

Answers (3)

Ropstah
Ropstah

Reputation: 17794

You can use jQuery for this:

$(document).ready(function(){  
    $("a[href^='http']:not([href*='"+location.hostname+"'])").attr("target","_blank");  
});  

It should match both http and https links.

Upvotes: 4

Svend
Svend

Reputation: 8158

I use a little JavaScript on my own site. I then have a style setup to modify the link (it adds a little image/globe, vaguely MSDN like. Making the link open in a new page would also be trivial by modifying the target attribute.

if (document.links) {              
    for (var i = 0; i < document.links.length; i++) {
        l = document.links[i].href;
        if (l.indexOf('http://www.mysite.com')!=0 &&
            l.indexOf('http://udv.mysite.com')!=0 &&
            l.indexOf('http://')==0 ) {
            c = document.links[i];
            if (c.className == "dontModify") continue;
            c.className = c.className + " external";
            if (c.title != "") {
                c.title = "External link: " + c.title;
            }
        }
    }
}

Upvotes: 2

thedz
thedz

Reputation: 5572

The specific code is going to determine whether or not you use pure DOM-scripting, or any Javascript frameworks. But generally, here is what you'd do:

  1. Set an onclick callback for all anchor.

  2. In your callback, check to see if the href attribute of the link goes to an external site. You can use any number of ways to do this, but the easiest is probably a simple regex on the URL.

  3. If not external, allow the link to progress as normal (i.e., return true and the like).

  4. If external, open in new window, and then return false.

Opening a new window in Javascript is easy:

window.open('http://www.google.com');

Upvotes: 1

Related Questions