Rewrite all target _blank links to use rel noopener

Published: 2021-12-30 20:14:04 +0000
Categories: Javascript,




It's fairly common for sites to include target=_blank in external link anchors, to indicate that the link should open in a new window/tab.

However, this practice is actually quite dangerous - the new site/window is able to access the original tab using Javascript (specifically window.opener, leading to techniques such as tabnapping. This can be prevented by including rel=noopener in link anchors.

I wrote this function some time ago to detect external links within the DOM on and ensure they use noopener. Whilst it's better to have explicitly included it, it seems reasonably safe to rely on the presence of javascript, as javascript would be required for any exploit of the issue.


function forceNoOpener(){
    /** Force any external links to use noopener (unless they specifically have opener in them)

    Browsers should do this by default really -

    This is done in JS, as it's easier, and on the basis you _shouldn't_ be able to exploit it not being there if you don't have JS

    var eles = document.getElementsByTagName('a');
    var href,srcrel,rel;

    var own=document.location.hostname;

    for (var i=0;i<eles.length; i++){

        if (eles[i].getAttribute('target') == "_blank"){
            href = eles[i].getAttribute('href');

            if (!href.startsWith("http")){

            href_url = new URL(href);
            if (href_url.hostname != own){
                // It's an external link

                rel = ''
                srcrel = eles[i].getAttribute('rel')
                if (srcrel){
                    rel = srcrel

                if (!rel.includes("opener")){
                    eles[i].setAttribute('rel',"noopener "+rel);

Usage Example



links, noopener,

Latest Posts

Copyright © 2022 Ben Tasker | Sitemap | Privacy Policy
Available at, http://phecoopwm6x7azx26ctuqcp6673bbqkrqfeoiz2wwk36sady5tqbdpqd.onion and http://snippets.bentasker.i2p
hit counter