Created
July 24, 2013 12:12
-
-
Save anselmh/6069971 to your computer and use it in GitHub Desktop.
Open all external links (different hostname than current page) in new tab/window with plain vanilla JavaScript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Open external links in new tab/window | |
*/ | |
// All http:// links should open in new tab/window. Internal links are relative. | |
var anchors = document.querySelectorAll('a'); | |
for (var i = 0; i < anchors.length; i++) { | |
if (anchors[i].host !== window.location.hostname) { | |
anchors[i].setAttribute('target', '_blank'); | |
} | |
} |
I've tested the codepen version, but it's not working correctly. I'm using it in an XML template in the following form.
<script type='text/javascript'>
/*<![CDATA[*/
function makeExternal(link) {
var url = link.getAttribute('href'),
host = window.location.hostname.toLowerCase(),
regex = new RegExp('^(?:(?:f|ht)tp(?:s)?\:)?//(?:[^\@]+\@)?([^:/]+)', 'im'),
match = url.match(regex),
domain = ((match ? match[1].toString() : ((url.indexOf(':') < 0) ? host : ''))).toLowerCase();
// Same domain
if (domain != host) {
link.setAttribute('target', '_blank');
}
}
for (var l = 0, links = document.querySelectorAll('a'), ll = links.length; l < ll; ++l ){
makeExternal(links[l]);
}
/*]]>*/
</script>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Indeed, the regex didn't work with
//
links yet (and had a typo as well). I set up a codepen with updated regex, seems to work fine with quite a lot of different URL formats now. Did I miss a format?http://codepen.io/jkphl/pen/dyqLu