jQuery add target="_blank" for outgoing link
Asked Answered
V

15

46

I need some help to create jquery script :)
I have some of link like this on my HTML.

<a href="http://google.com">Google</a>
<a href="/">Home</a>
<a href="http://www.gusdecool.com/">Home</a>
<a href="contactus.html">Contact Us</a>

And now i want jQuery to check all of the link on my page. if that link is outside of my server (my server is gusdecool.com). Then add target="_blank". and the result will be like this

<a href="http://google.com" target="_blank">Google</a>
<a href="/">Home</a>
<a href="http://www.gusdecool.com/">Home</a>
<a href="contactus.html">Contact Us</a>
Verrocchio answered 26/10, 2011 at 10:55 Comment(1)
Possible duplicate of How do I add target="_blank" to a link within a specified div?Pressey
I
71

assuming that all external links will start with http:// you could do this:

$('a[href^="http://"]').not('a[href*=gusdecool]').attr('target','_blank');

Iraqi answered 26/10, 2011 at 11:0 Comment(5)
nope, please see my comment for Joakim for the explanation :)Verrocchio
an external site could still start only with www and any other link that contains the gusdecool keyword (ex : a subdomain such as http://sub.gusdecool.com) is still considered external to the current webpage.Multilingual
I came across this thread after searching for a quick solution for external links and I think the selector should be $('a[href^="http://"], a[href^="https://"]'). to match https links as well.Generalship
This will not include https sites, you should probably just use $('a[href^="http"]').not('a[href*=gusdecool]').attr('target','_blank');Maquis
I needed to set "gusdecool" into single or double quotes to make the code work.Gauthier
F
19
$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if (!a.test(this.href)) {
      $(this).attr("target","_blank");
   }
});

This was from css-tricks.com, seems to work pretty well.

Feint answered 27/7, 2013 at 0:39 Comment(1)
I have two questions: 1) does this work with relative links like <a href="/">Home</a>? 2) why don't you put var a = new RegExp('/' + window.location.host + '/'); befor the loop?Ribbon
M
14
$('a[href^=http]:not([href^=http://www.gusdecool.com/])').attr('target','_blank');

Of course, this works only if all the external links start with the http protocol. You should adapt this code to suite your needs (suchs as links without protocols, or with different protocols).

UPDATE :

$('a[href^=http]:not([href^=http://www.gusdecool.com],[href^=http://gusdecool.com])')
    .add('a[href^=www]:not([href^=www.gusdecool.com])')
        .attr('target','_blank');

It selects all the a elements that have their href attribute starting with a web page address (with or without protocol) and do not point to your site's address and changes their target attribute to _blank.

Multilingual answered 26/10, 2011 at 11:1 Comment(3)
Nice jQuery selector! This should get voted above the selected correct answer as it is the best/fastest solution.Implosive
You might want to add "s? Because I'm getting unrecognized expressions.Resect
Using these jQuery selectors can affect javascript performance.Cuneate
B
13

This function seems to be easier if you have a subdomain:

$('a').attr('target', function() {
  if(this.host == location.host) return '_self'
  else return '_blank'
});
Businesswoman answered 28/6, 2015 at 12:51 Comment(1)
This is the best answer to me, since totally agnostic (i.e. not hard-written stuffs) and fully explicit. +1Onset
I
3
jQuery(document).ready(function(){
    target_luar();
});    
function target_luar(){
    try{
        if(top.location != location) {
            jQuery("a[href^='http']")
              .not("[href*='"+location.host+"']")
              .attr('target','_blank');
        }
    } catch(err) { }
}

Demo : Demo jQuery External Link

Inexpressive answered 11/5, 2012 at 3:2 Comment(0)
Q
3

Global function to open external links in a new window:

$(function(){ // document ready

    $("a").filter(function () {
        return this.hostname && this.hostname !== location.hostname;
    }).each(function () {
        $(this).attr({
            target: "_blank",
            title: "Visit " + this.href + " (click to open in a new window)"
        });
    });

});
Questioning answered 14/6, 2013 at 17:51 Comment(1)
A word of caution (applies to many solutions on this page): if you have a mailto link, it will also receive a target attribute, which could lead to undesirable behavior (in Chrome, it works but also opens an extra blank tab).Evante
C
3

Putting it all together we get the following.. Wait for it all to load, select only links starting with http or https, check if the link point to the same domain (internal) or another domain (external), add appropriate target if match found..

$(window).load(function() {
    $('a[href^="http"]').attr('target', function() {
      if(this.host == location.host) return '_self'
      else return '_blank'
    });
});
Corinnacorinne answered 2/10, 2018 at 16:42 Comment(1)
It would be great if you could provide a short explanation of your code!Gracegraceful
C
1

Check each linkobject $(link).attr("href"), if that starts with http:// then its an outgoing link (?). Then assign the .attr("target", "_blank").

$(a).function(){
    if($(this).attr("href").substring(0,3) == "http" && <!-- CHECK ITS NOT YOUR SITE URL -->){
       $(this).attr("target", "_blank"); 
    }
};

Hope this helps.

Chivalrous answered 26/10, 2011 at 10:59 Comment(5)
well kind of it is.. you will end up at the site, but it is still an outgoing link?Chivalrous
my purpose create this plugin is to make sure my visitor didn't leave my website if click a link except if that link target is inside of my website. That why i need to make special rule for outgoing link.Verrocchio
@Verrocchio I don't think its a very good idea to stop people leaving your site to go to external sites if they wish to. They will find other ways and get frustrated if you try and stop them. Or am I misunderstanding you?Iraqi
He doesn't want to stop people from leaving his site. He just want external links to be _blank to make it easy for them to find their way back to his site once they are done with the external link's site. Using _blank for that purpose would be one way to do it.Chivalrous
@JoakimBörjesson Thank you for explain it to Moin :)Verrocchio
H
1

You could use jQuery's $.each function to iterate over all Anchor tags, perform the needed check and set the "target" attribute using $(this).attr("target","_blank");

Example (Not tested but should work):

$('a').each(function(index) {
    var link = $(this).attr("href");
    if(link.substring(0,7) == "http://")
        $(this).attr("target", "_blank");
});

Shai.

Heteronomy answered 26/10, 2011 at 10:59 Comment(0)
S
1

Here's a fiddle demonstrating an answer using raw JS (not jQuery): http://jsfiddle.net/Xwqmm/

And here's the code:

var as = document.getElementsByTagName('a');
var re = /^https?:\/\/([^\/]*)\//;
for (var i = 0, l = as.length; i < l; i++) {
    var href = as[i].href;
    var matches = href.match(re);
    if (matches[1] && matches[1] != "gusdecool.com") {
        as[i].setAttribute("target","_blank");
    }
}
Scientistic answered 26/10, 2011 at 11:1 Comment(0)
A
1

This is such a brilliant site I learned so much from it :

If you do it this way you do not need to worry about http or https (handy while developing)

$('a[href^="http"]')
        .not('a[href*='+ location.hostname +']')
        .attr('target','_blank');

Anywhere answered 16/3, 2020 at 0:13 Comment(0)
A
1

You can see all external link whith http and https


jQuery('a[href^="https://"],a[href^="http://"]').not("a[href*='"+ window.location.host +"']").each(function() {
  
    console.log(jQuery(this).attr('href'))
});

And you can add _blank like this

jQuery('a[href^="https://"],a[href^="http://"]').not("a[href*='"+ window.location.host +"']").attr('_target','blank');
Anne answered 2/11, 2020 at 12:59 Comment(0)
D
0

You could use filter -

$("a").filter(function () {
    return this.indexOf('http://') > -1 && this.indexOf('gusdecool') == -1 
}).attr("target","_blank");  
Declass answered 26/10, 2011 at 11:3 Comment(0)
L
0

Try:

$('a[href^="http://"]')
        .not('a[href*='+ location.hostname +']')
        .attr('target','_blank');
Lindbom answered 17/5, 2013 at 14:15 Comment(0)
E
0
<div id="myLinks"><a href="http://google.com">Google</a><a href="/">Home</a><a href="http://www.gusdecool.com/">Home</a>
<a href="contactus.html">Contact Us</a></div>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#myLinks a').attr('target', '_blank');
});
</script>
Effeminate answered 16/3, 2016 at 7:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.