Skip to content

Instantly share code, notes, and snippets.

@gormus
Created January 25, 2020 00:55
Show Gist options
  • Save gormus/56abad6fc08fc763a37ff3ace2e464fa to your computer and use it in GitHub Desktop.
Save gormus/56abad6fc08fc763a37ff3ace2e464fa to your computer and use it in GitHub Desktop.
Add `rel="noopener"` to all "A" tags for external links. See https://gist.github.com/gormus/575844 for an old, similar gist
/**
* Add rel="noopener" to all "A" tags for external links.
*
* Selection rules:
* - "A" tag must have "href" attribute, exclude anchors.
* - "href" attribute must not start with a "."
* - "href" attribute must not start with a "/"
* - "A" tag must not have rel="noopener" set.
* - "A" tag must not have rel="noreferrer" set.
*
* @todo: Rewrite in plain javascript.
*/
$('a[href]').not("[href^='.'], [href^='/'], [rel=noopener], [rel=noreferrer]").each(function () {
var a = $(this),
r = a[0].rel ? a[0].rel + ' ' : '';
if (a[0].origin != window.location.origin) {
a[0].rel = r + 'noopener';
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment