Adding noopener to all external links

Hey guys

Is there some custom code I can add to make all external links on my site “noopener” or “noreferrer”?
As per recommendations from Google Lighthouse


To be clear, this is for all pages of our blog, not just static pages. So I’m guessing would require custom code.

Be great to hear people’s thoughts! :slight_smile:


Here is my site Read-Only: LINK
(how to share your site Read-Only link)

1 Like

@williamsbrad1994 found this on stackoverflow. This should work well, just change the re variable to your domain name in the same format.

function setRelAttribute() {
    var elems = document.body.getElementsByTagName('a');
    for (var i = 0; i < elems.length; i++) {
        var elem = elems[i]
        var re = /mydomain.com/
        var isInternal = re.test(elem.href)
        if (!isInternal) {
            elem.rel= 'noopener noreferrer nofollow'
        }
    }
}

document.addEventListener('DOMContentLoaded', function () {
    setRelAttribute()
}, false);
1 Like

Thanks for this! Worked right away (I also deleted the ‘nofollow’ tag)

:smiley:

@dennyhartanto What if we want to exclude some URLs from page?

@Mayur_Pokle you can try replacing
var re = /mydomain.com/
with

var re = /(domain.com|domaintwo.com|domain.three)/ 

add a ( ) and separate each domain with | (this is the straight line that shares the same button as a backslash "" on your keyboard)