Rewrite all target _blank links to use rel noopener (Javascript)

It's fairly common for sites to include 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 bentasker.co.uk 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.

Details

  • Language: Javascript

Snippet

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

    Browsers should do this by default really - https://bugs.chromium.org/p/chromium/issues/detail?id=898942

    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"){
            console.log(eles[i]);
            href = eles[i].getAttribute('href');

            if (!href.startsWith("http")){
                continue;
            }

            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

doDocumentReady(forceNoOpener);