11

What's the best way to open all external links (URLs that don't match the current domain) in a new tab using JavaScript, without using jQuery?

Here's the jQuery I'm current using:

// Open external links in new tab
$('a[href^=http]').click(function () {
    var a = new RegExp('/' + window.location.host + '/');
    if (!a.test(this.href)) {
        window.open(this.href);
        return false;
    }
});
Alec Rust
  • 10,532
  • 12
  • 48
  • 63

4 Answers4

25

Pure JS:

function externalLinks() {
  for(var c = document.getElementsByTagName("a"), a = 0;a < c.length;a++) {
    var b = c[a];
    b.getAttribute("href") && b.hostname !== location.hostname && (b.target = "_blank")
  }
}
;
externalLinks();
eyecatchUp
  • 10,032
  • 4
  • 55
  • 65
1

The links property returns a collection of all <area> and <a> elements in a document with a value for the href attribute.

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

https://developer.mozilla.org/en-US/docs/Web/API/Document/links

Manpreet
  • 2,450
  • 16
  • 21
0

Add a target="_blank" to the tag. You could do that in the pre-processor (e.g. PHP) or in a JS during the onload event.

Sebastian Meine
  • 11,260
  • 29
  • 41
  • Are you looking for a way to do the above in JavaScript but without using jQuery? If so, do you have any other library, or does it have to be plain JS? – Sebastian Meine Oct 20 '12 at 18:47
0
       $("a[href^=http]").each(function(){
          if(this.href.indexOf(location.hostname) == -1) {
             $(this).attr({
                target: "_blank",
                title: "Opens in a new window"
             });
          }
       })

This script should work for you.

UPDATE : try this fiddle http://jsfiddle.net/sameerast/GuT2y/

JS version

    var externalLinks = function(){
      var anchors = document.getElementsByTagName('a');
      var length = anchors.length;
      for(var i=0; i<length;i++){
        var href = anchor[i].href;
        if(href.indexOf('http://sample.com/') || href.indexOf('http://www.sample.com/')){
          return;
        }
        else{
          anchor[i].target='_blank';
        }
      }
    };
Sameera Thilakasiri
  • 9,452
  • 10
  • 51
  • 86