Test if links are external with jQuery / javascript?
Asked Answered
C

17

77

How do I test to see if links are external or internal? Please note:

  1. I cannot hard code the local domain.
  2. I cannot test for "http". I could just as easily be linking to my own site with an http absolute link.
  3. I want to use jQuery / javascript, not css.

I suspect the answer lies somewhere in location.href, but the solution evades me.

Thanks!

Cattegat answered 26/5, 2010 at 7:37 Comment(1)
do you want to check it when the link is clicked or on page load?Supereminent
A
66
var comp = new RegExp(location.host);

$('a').each(function(){
   if(comp.test($(this).attr('href'))){
       // a link that contains the current host           
       $(this).addClass('local');
   }
   else{
       // a link that does not contain the current host
       $(this).addClass('external');
   }
});

Note: this is just a quick & dirty example. It would match all href="#anchor" links as external too. It might be improved by doing some extra RegExp checking.


Update 2016-11-17

This question still got a lot of traffic and I was told by a ton of people that this accepted solution will fail on several occasions. As I stated, this was a very quick and dirty answer to show the principal way how to solve this problem. A more sophisticated solution is to use the properties which are accessible on a <a> (anchor) element. Like @Daved already pointed out in this answer, the key is to compare the hostname with the current window.location.hostname. I would prefer to compare the hostname properties, because they never include the port which is included to the host property if it differs from 80.

So here we go:

$( 'a' ).each(function() {
  if( location.hostname === this.hostname || !this.hostname.length ) {
      $(this).addClass('local');
  } else {
      $(this).addClass('external');
  }
});

State of the art:

Array.from( document.querySelectorAll( 'a' ) ).forEach( a => {
    a.classList.add( location.hostname === a.hostname || !a.hostname.length ? 'local' : 'external' );
});
Aflcio answered 26/5, 2010 at 7:55 Comment(14)
This works fairly well, although I'm going to hold off on an answer in case someone else has a more elegant solution. Out of curiosity, why do anchor links register as external?Cattegat
I'm pretty sure that this will not work with relative urls. attr is supposed to return the attribute, not the property (the property might be resolved, not the attribute).Nerty
jsfiddle.net/zuSeh It is verified that this method does not work for relative urls.Nerty
Just ran into this and want to confirm that this code indeed has a problem with relative urls. So +1 on Sean and Damian.Production
It will work for relative too if you use the href property instead of the href attribute.Catnap
I've seen people still viewing this question and solution so I wanted to link to my proposed solution below which should handle all checks without RegEx or relative issues: https://mcmap.net/q/264545/-test-if-links-are-external-with-jquery-javascriptSemirigid
jAndy's solution will also fail (false detection of internal link) in the case that an external URL contains the hostname, e.g. external-site.com/domaintools/original.hostname.com/stats or something like that. Overall I favour @Daved's solution as the most elegant and most direct check—far less error prone when the browser has already resolved the URL and you're checking its resolved hostname!Bitterling
Updated answer.Aflcio
@Aflcio I believe that, correct me if I'm wrong, there is no need for using Array.from in last part of your answer, instead just wrap the expression in parens to become (document.querySelectorAll( 'a' )).forEachEscaut
@MoAli At the time I wrote that, most browsers didn't provide the forEach method on the HTMLElement prototype. I still wouldn't dare to directly call that even today to be honest. Of course there are still some versions and mobile browsers which also don't support Array.from, but chances are way higher here, than .forEach being on the prototype.Aflcio
@Aflcio - Thanks for this solution. one more point is that if the href has relative URL having # in it, then it is not working. may you please give a solution for the same?Device
@jAndy, why do you check "!this.hostname.length". In chrome it's always not empty even if href does not have hostname. Can it be empty in some browser?Dynel
@Dynel I just did a quick check here on the SO site... If you filter all results from document.querySelectorAll( 'a' ).forEach( anchor => {}); for if( !anchor.hostname.length) you get lots of results. For instance anchors which only have a name or class but no href.Aflcio
@jAndy, thank you. I also tested it in IE11, link with href="/page1" does not have hostname property, unlike in Chrome.Dynel
S
75

I know this post is old but it still shows at the top of results so I wanted to offer another approach. I see all the regex checks on an anchor element, but why not just use window.location.host and check against the element's host property?

function link_is_external(link_element) {
    return (link_element.host !== window.location.host);
}

With jQuery:

$('a').each(function() {
    if (link_is_external(this)) {
        // External
    }
});

and with plain javascript:

var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
    if (link_is_external(links[i])) {
        // External
    }
}
Semirigid answered 6/9, 2013 at 15:9 Comment(10)
This is the only answer which makes sense to me -- the others are way overengineered. Are there any arguments against this method?Memoirs
The jQuery above works for me in Safari, and handles all of the issues that the others handle -- local anchors, relative URLs, cross-protocol URLs, etc. Note: example.com and example.com will be marked as internal; that may be important to you.Disaccharide
This is the best answer. This makes use of the a.host property which is probably unknown to the average JavaScript developer (including myself before reading this).Maintenon
Perfect, just what I was looking for! Clean and simple without all the regex hassle which isn't needed.Deragon
Works flawlessly. Best answer.Godfrey
this will fail when port number is specified, also if "www" is left outKo
I'm a little late to the follow up here, but I would argue to @Ko that "www" is an identifier that would indicate a different match. And though the domain might be the same, the host would be different with WWW and I think that's a valid condition. The port can be checked by using a ".port" comparison as well if they both != ''.Semirigid
@Memoirs Yes, I have just one argument against it, it depends on a DOM node. Imagine that I can have only the href string, I wouldn't be able to test it without creating a ghost node for it.Meatus
@Semirigid Looking back, maybe testing .origin of each would make most sense. That'll include the scheme and port.Memoirs
@giovannipds, you can use new URL(myHrefString) instead of a new DOM node.Memoirs
A
66
var comp = new RegExp(location.host);

$('a').each(function(){
   if(comp.test($(this).attr('href'))){
       // a link that contains the current host           
       $(this).addClass('local');
   }
   else{
       // a link that does not contain the current host
       $(this).addClass('external');
   }
});

Note: this is just a quick & dirty example. It would match all href="#anchor" links as external too. It might be improved by doing some extra RegExp checking.


Update 2016-11-17

This question still got a lot of traffic and I was told by a ton of people that this accepted solution will fail on several occasions. As I stated, this was a very quick and dirty answer to show the principal way how to solve this problem. A more sophisticated solution is to use the properties which are accessible on a <a> (anchor) element. Like @Daved already pointed out in this answer, the key is to compare the hostname with the current window.location.hostname. I would prefer to compare the hostname properties, because they never include the port which is included to the host property if it differs from 80.

So here we go:

$( 'a' ).each(function() {
  if( location.hostname === this.hostname || !this.hostname.length ) {
      $(this).addClass('local');
  } else {
      $(this).addClass('external');
  }
});

State of the art:

Array.from( document.querySelectorAll( 'a' ) ).forEach( a => {
    a.classList.add( location.hostname === a.hostname || !a.hostname.length ? 'local' : 'external' );
});
Aflcio answered 26/5, 2010 at 7:55 Comment(14)
This works fairly well, although I'm going to hold off on an answer in case someone else has a more elegant solution. Out of curiosity, why do anchor links register as external?Cattegat
I'm pretty sure that this will not work with relative urls. attr is supposed to return the attribute, not the property (the property might be resolved, not the attribute).Nerty
jsfiddle.net/zuSeh It is verified that this method does not work for relative urls.Nerty
Just ran into this and want to confirm that this code indeed has a problem with relative urls. So +1 on Sean and Damian.Production
It will work for relative too if you use the href property instead of the href attribute.Catnap
I've seen people still viewing this question and solution so I wanted to link to my proposed solution below which should handle all checks without RegEx or relative issues: https://mcmap.net/q/264545/-test-if-links-are-external-with-jquery-javascriptSemirigid
jAndy's solution will also fail (false detection of internal link) in the case that an external URL contains the hostname, e.g. external-site.com/domaintools/original.hostname.com/stats or something like that. Overall I favour @Daved's solution as the most elegant and most direct check—far less error prone when the browser has already resolved the URL and you're checking its resolved hostname!Bitterling
Updated answer.Aflcio
@Aflcio I believe that, correct me if I'm wrong, there is no need for using Array.from in last part of your answer, instead just wrap the expression in parens to become (document.querySelectorAll( 'a' )).forEachEscaut
@MoAli At the time I wrote that, most browsers didn't provide the forEach method on the HTMLElement prototype. I still wouldn't dare to directly call that even today to be honest. Of course there are still some versions and mobile browsers which also don't support Array.from, but chances are way higher here, than .forEach being on the prototype.Aflcio
@Aflcio - Thanks for this solution. one more point is that if the href has relative URL having # in it, then it is not working. may you please give a solution for the same?Device
@jAndy, why do you check "!this.hostname.length". In chrome it's always not empty even if href does not have hostname. Can it be empty in some browser?Dynel
@Dynel I just did a quick check here on the SO site... If you filter all results from document.querySelectorAll( 'a' ).forEach( anchor => {}); for if( !anchor.hostname.length) you get lots of results. For instance anchors which only have a name or class but no href.Aflcio
@jAndy, thank you. I also tested it in IE11, link with href="/page1" does not have hostname property, unlike in Chrome.Dynel
N
37

And the no-jQuery way

var nodes = document.getElementsByTagName("a"), i = nodes.length;
var regExp = new RegExp("//" + location.host + "($|/)");
while(i--){
    var href = nodes[i].href;
    var isLocal = (href.substring(0,4) === "http") ? regExp.test(href) : true;
    alert(href + " is " + (isLocal ? "local" : "not local"));
}

All hrefs not beginning with http (http://, https://) are automatically treated as local

Nerty answered 26/5, 2010 at 8:18 Comment(5)
This answer is more accurate. Relatives URL are also important.Baxy
If I'm not mistaken, "($|/" should actually be "($|/)" with a closing braceProduction
This is close to the solution but you should also check if the href property does begin with location.protocol+'//'+location.host. Check this fiddle: jsfiddle.net/framp/Ag3BT/1Blossom
Why are you doing this with a while loop? Seems to me like it would make more sense to use event delegation via $(document).on('click', 'a', function({}); and test the specific link that was clicked (at the point of being clicked). That way, you don't needlessly loop through all the links on the page, and it will allow for any elements added to the page via ajax after the initial DOM ready... There's actually a point to using jQuery sometimes (beyond being a "fanboy").Nicole
This won't work if you use protocol agnostic urls, ie: href="//somedomain.com/some-path"Ansela
N
9
var external = RegExp('^((f|ht)tps?:)?//(?!' + location.host + ')');

Usage:

external.test('some url'); // => true or false
Neology answered 26/5, 2010 at 8:28 Comment(1)
+1 for the regexp, though it does not completely solve the questionGilud
N
7

Here's a jQuery selector for only external links:

$('a[href^="(http:|https:)?//"])') 

A jQuery selector only for internal links (not including hash links within the same page) needs to be a bit more complicated:

$('a:not([href^="(http:|https:)?//"],[href^="#"],[href^="mailto:"])')

Additional filters can be placed inside the :not() condition and separated by additional commas as needed.

http://jsfiddle.net/mblase75/Pavg2/


Alternatively, we can filter internal links using the vanilla JavaScript href property, which is always an absolute URL:

$('a').filter( function(i,el) {
    return el.href.indexOf(location.protocol+'//'+location.hostname)===0;
})

http://jsfiddle.net/mblase75/7z6EV/

Nowlin answered 6/6, 2014 at 15:9 Comment(3)
+1: OK there was a way to up-vote you again for this answer :)Gregale
First one doesn't work as "//code.jquery.com/jquery.min.js" is a completely legit URL, but not internal. The protocol and colon are not required, as the browser will use whatever the current site is using (a semi-sorta protocol relative URL).Northwester
FYI, your external selector gives an error: Uncaught Error: Syntax error, unrecognized expression: a[href^="(http:|https:)?//"])Crotch
P
6

You forgot one, what if you use a relative path.

forexample: /test

        hostname = new RegExp(location.host);
            // Act on each link
            $('a').each(function(){

            // Store current link's url
            var url = $(this).attr("href");

            // Test if current host (domain) is in it
            if(hostname.test(url)){
               // If it's local...
               $(this).addClass('local');
            }
            else if(url.slice(0, 1) == "/"){
                $(this).addClass('local'); 
            }
            else if(url.slice(0, 1) == "#"){
                // It's an anchor link
                $(this).addClass('anchor'); 
            }
            else {
               // a link that does not contain the current host
               $(this).addClass('external');                        
            }
        });

There are also the issue of file downloads .zip (local en external) which could use the classes "local download" or "external download". But didn't found a solution for it yet.

Pekan answered 6/11, 2012 at 13:48 Comment(1)
Not all relative URLs start with /. You can reference something like images/logo.png which is one folder down from your current location. In that case you're referencing a relative path in your relative URL, it will be a different meaning in different directories on your site. /images/logo.png is an absolute path of whatever site it's running on (hence the relativity). Your code will not include relative paths like images/logo.png.Wholewheat
O
6
const isExternalLink = (url) => {
    const tmp = document.createElement('a');
    tmp.href = url;
    return tmp.host !== window.location.host;
};

// output: true
console.log(isExternalLink('https://foobar.com'));
console.log(isExternalLink('//foobar.com'));

// output: false
console.log(isExternalLink('https://www.stackoverflow.com'));
console.log(isExternalLink('//www.stackoverflow.com'));
console.log(isExternalLink('/foobar'));
console.log(isExternalLink('#foobar'));

The benefit of using this approach is that:

  • It would automatically resolve the hostname for relative paths and fragments;
  • It works with protocol-relative URLs

To demonstrate this, let's look at the following examples:

const lnk = document.createElement('a');
lnk.href = '/foobar';

console.log(lnk.host); // output: 'www.stackoverflow.com'
const lnk = document.createElement('a');
lnk.href = '#foobar';

console.log(lnk.host); // output: 'www.stackoverflow.com'
const lnk = document.createElement('a');
lnk.href = '//www.stackoverflow.com';

console.log(lnk.host); // output: 'www.stackoverflow.com'
Outsell answered 26/12, 2021 at 12:18 Comment(0)
S
4

With jQuery

jQuery('a').each(function() {
    if (this.host !== window.location.host) {
        console.log(jQuery(this).attr('href'));
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Shedevil answered 26/12, 2021 at 11:27 Comment(1)
A good answer will always include an explanation why this would solve the issue, so that the OP and any future readers can learn from it.Gosse
M
3

You can use is-url-external module.

var isExternal = require('is-url-external');
isExternal('http://stackoverflow.com/questions/2910946'); // true | false 
Mascot answered 19/12, 2016 at 14:32 Comment(0)
S
2

/**
     * All DOM url
     * [links description]
     * @type {[type]}
     */
    var links = document.querySelectorAll('a');
    /**
     * Home Page Url
     * [HomeUrl description]
     * @type {[type]}
     */
    var HomeUrl = 'https://stackoverflow.com/'; // Current Page url by-> window.location.href

    links.forEach(function(link) {
        link.addEventListener('click', function(e) {
            e.preventDefault();

            // Make lowercase of urls
            var url = link.href.toLowerCase();
            var isExternalLink = !url.includes(HomeUrl);

            // Check if external or internal
            if (isExternalLink) {
                if (confirm('it\'s an external link. Are you sure to go?')) {
                    window.location = link.href;
                }
            } else {
                window.location = link.href;
            }
        })
    })
<a href="https://stackoverflow.com/users/3705299/king-rayhan">Internal Link</a>
<a href="https://wordpress.stackexchange.com/">External Link</a>
Squamation answered 17/3, 2018 at 8:8 Comment(1)
This is a worthy answer which could use its own space...Oden
A
2

This should work for any kind of link on every browser except IE.

// check if link points outside of app - not working in IE
                try {
                    const href = $linkElement.attr('href'),
                        link = new URL(href, window.location);

                    if (window.location.host === link.host) {
                        // same app
                    } else {
                        // points outside
                    }
                } catch (e) { // in case IE happens}
Ables answered 1/10, 2018 at 12:0 Comment(1)
Note to new URL(href, window.location): Argument of type 'Location' is not assignable to parameter of type 'string | URL | undefined'.Lucianolucias
B
0

Yes, I believe you can retrieve the current domain name with location.href. Another possibility is to create a link element, set the src to / and then retrieving the canonical URL (this will retrieve the base URL if you use one, and not necessarily the domain name).

Also see this post: Get the full URI from the href property of a link

Baxy answered 26/5, 2010 at 7:42 Comment(0)
G
0

For those interested, I did a ternary version of the if block with a check to see what classes the element has and what class gets attached.

$(document).ready(function () {
    $("a").click(function (e) {

        var hostname = new RegExp(location.host);
        var url = $(this).attr("href");

        hostname.test(url) ?
        $(this).addClass('local') :
        url.slice(0, 1) == "/" && url.slice(-1) == "/" ?
        $(this).addClass('localpage') :
        url.slice(0, 1) == "#" ?
        $(this).addClass('anchor') :
        $(this).addClass('external');

        var classes = $(this).attr("class");

        console.log("Link classes: " + classes);

        $(this).hasClass("external") ? googleAnalytics(url) :
        $(this).hasClass("anchor") ? console.log("Handle anchor") : console.log("Handle local");

    });
});

The google analytics bit can be ignored but this is where you'd probably like to do something with the url now that you know what type of link it is. Just add code inside the ternary block. If you only want to check 1 type of link then replace the ternaries with an if statement instead.

Edited to add in an issue I came across. Some of my hrefs were "/Courses/" like so. I did a check for a localpage which checks if there is a slash at the start and end of the href. Although just checking for a '/' at the start is probably sufficient.

Gut answered 23/3, 2016 at 10:48 Comment(0)
L
0

I use this function for jQuery:

$.fn.isExternal = function() {
  var host = window.location.host;
  var link = $('<a>', {
    href: this.attr('href')
  })[0].hostname;
  return (link !== host);
};

Usage is: $('a').isExternal();

Example: https://codepen.io/allurewebsolutions/pen/ygJPgV

Lianneliao answered 3/10, 2017 at 22:22 Comment(0)
A
0

This doesn't exactly meet the "cannot hardcode my domain" prerequisite of the question, but I found this post searching for a similar solution, and in my case I could hard code my url. My concern was alerting users that they are leaving the site, but not if they are staying on site, including subdomains (example: blog.mysite.com, which would fail in most of these other answers). So here is my solution, which takes some bits from the top voted answers above:

Array.from( document.querySelectorAll( 'a' ) ).forEach( a => {
  a.classList.add( a.hostname.includes("mywebsite.com") ? 'local' : 'external' );
});

$("a").on("click", function(event) {
  if ($(this).hasClass('local')) {
    return;
  } else if ($(this).hasClass('external')) {
    if (!confirm("You are about leave the <My Website> website.")) {
      event.preventDefault();
    }
  }
});
Audly answered 24/1, 2020 at 16:11 Comment(0)
M
0

this works for me:

function strip_scheme( url ) {
    return url.replace(/^(?:(?:f|ht)tp(?:s)?\:)?\/\/(www\.)?/g, '');
  }

  function is_link_external( elem ) {
    let domain = strip_scheme( elem.attr('href') );
    let host = strip_scheme( window.location.host );

    return ! domain.indexOf(host) == 0;
  }
Millett answered 31/5, 2022 at 8:23 Comment(0)
H
0

As of 2023, doing this did the job for me

export function isInternalLink(urlString: string): boolean | {
  pathname: string;
} {
  const url = new URL(urlString);
  if (url.origin !== window.location.origin) {
    return false;
  }
  return {
    pathname: url.pathname,
  };
}

Hennebery answered 20/6, 2023 at 3:41 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.