window.opener.close()无效

1.父页面window.open()打开新页面

var targetWeb=null;
if(targetWeb){
    targetWeb.focus();
}else{
    targetWeb=window.open('https://segmentfault.com','segmentfault');
}

2.子页面中关闭父页面

window.opener.close();

发现子页面无法关闭父页面,会提示:Scripts may close only the windows that were opened by it
但若换成:window.opener.location.href='https://www.hao123.com' 却可以,请问是什么原因

阅读 8k
4 个回答

还是在一本书上找到了答案:浏览器的主窗口,在没有得到用户的允许时不能关闭它。弹窗是可以不经过用户的允许关闭自己。

新手上路,请多包涵

clipboard.png

close 方法只能关闭由自己打开的window

<html>
<body>

<script type="text/javascript">
myWindow=window.open('','','width=200,height=100');
myWindow.document.write("This is 'myWindow'");
myWindow.document.write("<script>window.opener.close()</script>");
myWindow.focus();
myWindow.opener.document.write("This is the parent window");
myWindow.close();
</script>

</body>
</html>


尝试了这段代码,在父窗口中直接使用
 myWindow=window.open('','','width=200,height=100');
    myWindow.close();

可以关掉子窗口,在子窗口中无效。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题