Skip to content

Instantly share code, notes, and snippets.

@dsturm
Forked from allybee/target_blank.js
Last active October 26, 2017 15:15
Show Gist options
  • Save dsturm/32153ef5d8818abbb37b13b6250a78fb to your computer and use it in GitHub Desktop.
Save dsturm/32153ef5d8818abbb37b13b6250a78fb to your computer and use it in GitHub Desktop.
Add target="_blank" to external links with pure JavaScript.
function targetBlank() {
// remove subdomain of current site's url and setup regex
var internal = location.host.replace(/^[^.]+\./g, '');
internal = new RegExp(internal, "i");
var a = document.getElementsByTagName('a'); // then, grab every link on the page
for (var i = 0; i < a.length; i++) {
var href = a[i].host; // set the host of each link
if (!internal.test(href)) {
// make sure the href doesn't contain current site's host
a[i].setAttribute('target', '_blank'); // if it doesn't, set attributes
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment