Make links to other websites open in a new tab, with the safe rel attributes and a hidden notice for screen reader users.
document.addEventListener( 'DOMContentLoaded', () => {
document.querySelectorAll( 'a[href^="http"]' ).forEach( ( link ) => {
if ( link.hostname === window.location.hostname || link.target ) {
return;
}
link.target = '_blank';
link.relList.add( 'noopener', 'noreferrer' );
const notice = document.createElement( 'span' );
notice.className = 'screen-reader-text';
notice.textContent = ' (opens in a new tab)';
link.appendChild( notice );
} );
} );
Some sites prefer external links to open in a new tab so visitors don’t lose their place. This script does it for every outgoing link, in a way that’s safe and tells screen reader users what will happen.
The script checks every link whose address starts with “http”. If it points to another domain and doesn’t already have a target, it gets target="_blank" and rel="noopener noreferrer", which stops the new page controlling yours.
A visually hidden “(opens in a new tab)” is added inside the link, using WordPress’s standard screen-reader-text class, so screen reader users aren’t surprised by a new tab.
.screen-reader-text class. WordPress themes are required to.Click an external link on your site. It should open in a new tab, and inspecting it should show the rel attribute and hidden text.