Created
October 24, 2017 17:07
-
-
Save asmattic/d7e60305ac0fd3d10f13da3ac8a8b7ff to your computer and use it in GitHub Desktop.
Make all external links on the page open in new tabs
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
let links = document.querySelectorAll('a') | |
// check if link is external | |
const currentHostname = window.location.hostname | |
// If has subdomain, split that off | |
const sliceSubdomain = currentHostname.slice(currentHostname.indexOf('.') + 1) | |
const hostname = (sliceSubdomain.includes('.')) ? sliceSubdomain : currentHostname | |
// Add target="_blank" to external links | |
links.forEach(link => { | |
const href = link.getAttribute('href') | |
// Could be some more checking for internal links that don't have hostname | |
if(!href.includes(hostname) && href.includes('http')) link.setAttribute('target','_blank') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment