Automatically Add rel=”noopener” to a target=”_blank” Link with JavaScript

12/29/2021

Contents

In this article, you will learn how to automatically add rel=”noopener” to a target=”_blank” link with JavaScript.

What is rel = “noopener”?

When you transition a page with target = “_ blank”, you can view and operate the page information (window.opener object) of the transition source on the transition destination page.
The rel = “noopener” is a security measure that sets the information of the window.opener object not to be viewed on the transition destination page.

In the latest browser, window.opener is not set if the target of the a tag is _blank.

Automatically add rel=”noopener” to a target=”_blank” link

If _blank is specified in the target attribute of a tag, try to automatically add noopener of rel attribute.

In the sample below, target = “_ blank” is specified in advance for the odd-numbered a tag, and noopener is added.

HTML

<ul>
    <li><a href="https://www.google.com/" target="_blank"> https://www.google.com/</a></li>
    <li><a href="https://www.yahoo.co.jp/"> https://www.yahoo.co.jp/</a></li>
    <li><a href="https://www.bing.com/" target="_blank"> https://www.bing.com/</a></li>
</ul>

JavaScript

const elements = document.getElementsByTagName('a');

for(let element of elements){
    let target = element.getAttribute('target');
    
    if(target === '_blank'){
        element.setAttribute('rel', 'noopener');
        //element.setAttribute('rel', 'noopener noreferrer');
    }
}