Question

I'm opening a popup from my main page with code like this:

<a href="http://external.domain.tld/"
   onclick="window.open(this.href, '_blank', 
       'width=512,height=512,left=200,top=100');return false">
 Open popup
</a>

This works fine, but my problem is that the document which is loaded in the popup window has the permission to change the location of the opener window. This even works when the document in the popup is from a different domain. It has no permission to read the location but it is allowed to change the location. I don't want that. I want the popup to be completely disconnected from my main page.

Even without JavaScript it doesn't work. When I open the other page in a new tab by using the target="_blank" attribute then this tab is still allowed to navigate to the opener window and change its location:

<a href="http://external.domain.tld/" target="_blank">
  Open in new tab
</a>

This is the code in the opened document which should not be allowed:

<script>
  opener.location.href = "http://badsite.tld/";
</script>

You can see a live demo here. Click one of the two links to open an other page in a popup or a new tab which then loads a third page in the opener window. That's what I'm trying to prevent.

Is there some trick I can use to break the connection between the opener window and the opened window? Ideally the opened window should not know that it was opened by any other window at all.

Was it helpful?

Solution

If the page in the child window is in your control, you can assign null to the opener in the child page:

window.opener = null;

By making this as the first statement in your javascript.

If the page is not in your control or is in a different domain, then do it while opening:

popup = window.open(this.href, '_blank', 'width=512,height=512,left=200,top=100');
popup.opener = null;

OTHER TIPS

From doc:

In some browsers, a rel="noopener" attribute on the originating anchor tag will prevent the window.opener reference from being set.

See all supported browsers: https://caniuse.com/#search=noopener

Also, for older browsers use no-referrer: https://mathiasbynens.github.io/rel-noopener/

So the fix is do rel="noreferrer noopener" wherever you are using target="_blank"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top