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



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.


    <li><a href="" target="_blank"></a></li>
    <li><a href=""></a></li>
    <li><a href="" target="_blank"></a></li>


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');