How to disconnect JavaScript popup from opener

拜拜、爱过 提交于 2019-11-30 08:35:33

问题


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.


回答1:


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;



回答2:


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"



来源:https://stackoverflow.com/questions/18121328/how-to-disconnect-javascript-popup-from-opener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!