Skip to content

Instantly share code, notes, and snippets.

@jryio
Created December 5, 2015 09:20
Show Gist options
  • Save jryio/4ad55d2030f488df8e12 to your computer and use it in GitHub Desktop.
Save jryio/4ad55d2030f488df8e12 to your computer and use it in GitHub Desktop.
Using JavaScript to open links (not within the host site) in a new tab
// Adds attribute "target=_blank" to links to all external sites
function handleExternalLinks () {
var host = location.host
var allLinks = document.querySelectorAll('a')
forEach(allLinks, function (elem, index) {
checkExternalLink(elem, host)
})
}
function checkExternalLink (item, hostname) {
var href = item.href
var itemHost = href.replace(/https?:\/\/([^\/]+)(.*)/, '$1')
if (itemHost !== '' && itemHost !== hostname) {
item.target = '_blank'
}
}
// NodeList forEach function
function forEach (array, callback, scope) {
for (var i = 0; i < array.length; ++i) {
callback.call(scope, array[i], i)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment