Created
December 5, 2015 09:20
-
-
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
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
// 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