Created
September 30, 2021 18:26
-
-
Save ao5357/990c450bec640e92c10b0a3b856be40d to your computer and use it in GitHub Desktop.
Vanilla JS way to make external links not leak info to their destinations
This file contains 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
/** | |
* Give external links target="_blank" and rel="noopener" | |
* | |
* @type {NodeListOf<HTMLElementTagNameMap[string]>} | |
*/ | |
const allAnchors = document.querySelectorAll('a'); | |
if (allAnchors.length) { | |
Array.prototype.forEach.call(allAnchors, (thisAnchor) => { | |
if (thisAnchor.href.length | |
&& thisAnchor.hostname !== window.location.hostname | |
&& thisAnchor.href.substring(0, 6) !== 'mailto' | |
&& thisAnchor.href.substring(0, 3) !== 'tel' | |
&& thisAnchor.href.substring(0, 1) !== '#' | |
) { | |
thisAnchor.setAttribute('target', '_blank'); | |
thisAnchor.setAttribute('rel', 'external noopener noreferrer'); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment