All Articles Kinsa Creative

JavaScript to Open External Links in a New Tab

Query all links with an href that is not the same as the current host and set target="_blank" rel="noopener,noreferral" on them. This follows Google's recommendations for security best practices when linking using target="_blank".

function handleExternalLinks() {
    const currentHost = window.location.host;
    // exclude links that are set up as links to start a call, start an email, navigate to an anchor, or navigate to a page without a domain
    document.querySelectorAll( `a:not([href*="${currentHost}"]):not([href^="tel:"]):not([href^="mailto:"]):not([href^="#"]):not([href^="/"])` ).forEach( ( a ) => {
        a.setAttribute( 'target', '_blank' );
        a.setAttribute( 'rel', 'noopener noreferrer' );
    } );
}

if ( document.readyState === 'loading' ) {
    // Loading hasn't finished yet, set an event listener
    document.addEventListener( 'DOMContentLoaded', handleExternalLinks );
} else {
    // `DOMContentLoaded` has already fired, run the func directly
    handleExternalLinks();
}

Feedback?

Email us at enquiries@kinsa.cc.