Open external links in a new tab
Make links to other websites open in a new tab with rel="noopener", using a few lines of JavaScript and no plugin.
// Open links to other websites in a new tab, and add rel="noopener".
( function () {
function snipfireExternalLinks() {
var links = document.querySelectorAll( 'a[href]' );
links.forEach( function ( link ) {
var isWeb = link.protocol === 'http:' || link.protocol === 'https:';
if ( ! isWeb || link.hostname === window.location.hostname || link.hasAttribute( 'target' ) ) {
return;
}
var rel = ( link.getAttribute( 'rel' ) || '' ).split( /\s+/ ).filter( Boolean );
if ( rel.indexOf( 'noopener' ) === -1 ) {
rel.push( 'noopener' );
}
link.setAttribute( 'target', '_blank' );
link.setAttribute( 'rel', rel.join( ' ' ) );
} );
}
if ( document.readyState === 'loading' ) {
document.addEventListener( 'DOMContentLoaded', snipfireExternalLinks );
} else {
snipfireExternalLinks();
}
} )();
What it does
Some site owners want links to other websites to open in a new tab, so visitors don't leave. Setting it on every link by hand is slow and easy to forget.
This script finds every link to another domain, adds target="_blank" and adds noopener to its rel attribute. Links to your own site, email links and links that already have a target aren't changed.
Good to know
- Links to subdomains, such as shop.example.com from example.com, count as external.
- Opening new tabs can confuse screen reader users. Consider saying "opens in a new tab" in the link text for important links.