Using rel="noopener" in window.open()

16.7k views Asked by At

So I know that I can apply rel="noopener in an a tag when using target="_blank". But I'm trying to pass it as an argument to window.open(), ie:

window.open('http://cats.com', '_blank', 'rel=noopener')

however it doesn't seem to be working the way that I expected, as the opener object still exists on the window after the user clicks on the link.

Is there something I'm missing? Or cannot it not be done the way that I'm intending?

I've found some great articles but they don't quite address my use case as far as I can tell.

https://developer.mozilla.org/en-US/docs/Web/API/Window/open https://mathiasbynens.github.io/rel-noopener/

Much appreciated.

4

There are 4 answers

1
Nauman Rafique On BEST ANSWER

There is no direct example in doc but it can be used like this and it worked for me.

window.open('http://cats.com', '_blank', 'noopener,resizable,scrollbars')
1
Cl Local On

As far as I know, this cannot be achieved with window.open() arguments. There is, however, is a way to get the behavior:

var newWindow = window.open();
newWindow.opener = null;
newWindow.location = 'http://some.url';
2
Chet On

This worked for me:

const a = document.createElement("a")
a.href = args.url
a.target = "_blank"
a.rel = "noopener"
a.click()
1
Gibolt On

Cover all your bases

The safest way to redirect is by adding noopener, noreferrer, and window.opener = null.

const openInNewTab = (url) => {
    const newWindow = window.open(url, '_blank', 'noopener,noreferrer')
    if (newWindow) newWindow.opener = null
}

Then call your new funtion

openInNewTab('https://stackoverflow.com')

The third param can also take these optional values, based on your needs.