What\'s the fastest method to detect if foo=\'http://john.doe\' is an external url (in comparsion to window.location.href)?
I had to build on pseudosavant's and Jon's answers because, I needed to also catch cases of URLs beginning with "//" and URLs that do not include a sub-domain. Here's what worked for me:
var getDomainName = function(domain) {
var parts = domain.split('.').reverse();
var cnt = parts.length;
if (cnt >= 3) {
// see if the second level domain is a common SLD.
if (parts[1].match(/^(com|edu|gov|net|mil|org|nom|co|name|info|biz)$/i)) {
return parts[2] + '.' + parts[1] + '.' + parts[0];
}
}
return parts[1]+'.'+parts[0];
};
var isExternalUrl = function(url) {
var curLocationUrl = getDomainName(location.href.replace("http://", "").replace("https://", "").replace("//", "").split("/")[0].toLowerCase());
var destinationUrl = getDomainName(url.replace("http://", "").replace("https://", "").replace("//", "").split("/")[0].toLowerCase());
return !(curLocationUrl === destinationUrl)
};
$(document).delegate('a', 'click', function() {
var aHrefTarget = $(this).attr('target');
if(typeof aHrefTarget === 'undefined')
return;
if(aHrefTarget !== '_blank')
return; // not an external link
var aHrefUrl = $(this).attr('href');
if(aHrefUrl.substr(0,2) !== '//' && (aHrefUrl.substr(0,1) == '/' || aHrefUrl.substr(0,1) == '#'))
return; // this is a relative link or anchor link
if(isExternalUrl(aHrefUrl))
alert('clicked external link');
});
Internal URLs:
- stackoverflow.com/questions/6238351/fastest-way-to-detect-external-urls
- www.stackoverflow.com/questions/6238351/fastest-way-to-detect-external-urls
- //stackoverflow.com/questions/6238351/fastest-way-to-detect-external-urls
- //www.stackoverflow.com/questions/6238351/fastest-way-to-detect-external-urls
External URLs: