<img height="1" width="1" style="display:none;" alt="" src="https://ct.pinterest.com/v3/?event=init&amp;tid=2612994575055&amp;pd[em]=<hashed_email_address>&amp;noscript=1">
Skip to content
    AdminOct 11, 2023 9:26:47 AM< 1 min read

    Boosting Website Security: Automatically Add rel='noopener noreferrer' to External Links

    To optimize the code and make it cover all possible scenarios, you can make several improvements:

    Step 1:

    Use a DOMContentLoaded event and not load event to make sure the code runs as soon as the DOM is ready, which will ensure it runs before Google bots scan the page.

    Step 2:

    Make the selector catch all external links that open in a new tab 

    Step 3:

    Optimize the conditional logic for better readability and performance.

    
    document.addEventListener("DOMContentLoaded", function() {
        document.querySelectorAll('a[target="_blank"]').forEach((link) => {
            let currentRel = link.getAttribute("rel") || "";
            let newRel = "noopener noreferrer";
    
            if (currentRel) {
                let relArray = currentRel.split(" ").map(item => item.trim().toLowerCase());
                if (relArray.includes("noopener")) newRel = newRel.replace("noopener", "");
                if (relArray.includes("noreferrer")) newRel = newRel.replace("noreferrer", "");
                newRel = currentRel + " " + newRel.trim();
            }
    
            link.setAttribute("rel", newRel.trim());
        });
    });
    

    The pervious code should effectively add rel="noopener noreferrer" to all external links that open in a new browser tab and load before Google bots scan the page.

    COMMENTS

    RELATED ARTICLES