Created
August 10, 2017 19:54
-
-
Save wpscholar/8d230deaa9703626c28c32b85070d416 to your computer and use it in GitHub Desktop.
JS for handling empty links, PDF links and external links
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
(function (win, doc) { | |
doc.addEventListener('DOMContentLoaded', () => { | |
// Prevent empty links from doing anything | |
[].forEach.call(doc.querySelectorAll('a[href="#"]'), function (el) { | |
el.addEventListener('click', function (e) { | |
e.preventDefault(); | |
}); | |
}); | |
// Force all PDF links to download automatically, if the browser supports it. Otherwise, open in a new tab. | |
[].forEach.call(doc.querySelectorAll('a[href$=".pdf"]'), function (el) { | |
el.setAttribute('download', ''); | |
el.setAttribute('target', '_blank'); | |
}); | |
// Force all external links to open in a new url (securely) | |
[].forEach.call(doc.querySelectorAll('a[href]'), function (el) { | |
if (el.getAttribute('href').substr(0, 7) !== 'mailto:') { | |
var isInternalLink = new RegExp('/' + window.location.host + '/'); | |
if (!isInternalLink.test(el.href)) { | |
el.setAttribute('target', '_blank'); | |
el.setAttribute('rel', 'noopener noreferrer'); | |
} | |
} | |
}); | |
}); | |
})(window, window.document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment