window.opener !== window 仅在 Mozilla 中定位为“_self”

我使用 window.open 作为目标“ _self ”从父窗口打开了一个子窗口,当我尝试console.log(window.opener !== window)在子窗口中打开它时,它在Mozilla 中返回 false ,但工作正常并在chrome 中返回true。


我想要的是原始父窗口实例的引用。


<!DOCTYPE html>

<html>

  <head>

    <title>Parcel Sandbox</title>

    <meta charset="UTF-8" />

  </head>


  <body>

    <div id="app"></div>

    <button onclick="myFunction()">Try it</button>


    <script>

      function myFunction() {

        var wnd = window.open("about:blank", "_self");

        wnd.document.write(

          "blank\<script\>alert(window.opener !== window)\</script\>"

        );

        console.log(wnd);

      }

    </script>

  </body>

</html>


繁华开满天机
浏览 227回答 2
2回答

慕妹3242003

根据mdn使用说明当一个窗口从另一个窗口打开时(使用 Window.open 或具有其目标属性集的链接),它维护对第一个窗口的引用作为 window.opener。如果当前窗口没有开启器,则此方法返回 null。所以我希望window.open以自我为目标null,因此window.opener !== window // 真无论是错误还是有意 - FF68.0.1 和 Chrome75.0.3770.142 似乎没有同意作为一种解决方法模拟_opener?<!DOCTYPE html><html>&nbsp; <head>&nbsp; &nbsp; <title>Parcel Sandbox</title>&nbsp; &nbsp; <meta charset="UTF-8" />&nbsp; </head>&nbsp; <body>&nbsp; &nbsp; <div id="app"></div>&nbsp; &nbsp; <button onclick="myFunction()">Try it</button>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; function myFunction() {&nbsp; &nbsp; &nbsp; &nbsp; window._opener = window.open("about:blank", "_self");&nbsp; &nbsp; &nbsp; &nbsp;window._opener.document.write(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "blank\<script\>alert(window._opener !== window)\</script\>"&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </script>&nbsp; </body></html>

12345678_0001

引用 MDN:如果同名的窗口已经存在,则strUrl加载到现有窗口中。在这种情况下,该方法的返回值是现有窗口并被strWindowFeatures忽略。提供空字符串strUrl是一种通过名称获取对打开窗口的引用而不更改窗口位置的方法。所以当你做window.open(url, '_self');您实际上只是将当前的 window 设置为 this url,但 Window 对象不会更改。btn.onclick = e => {&nbsp; const wnd = window.open('', '_self'); // let's not change the url&nbsp; console.log(window === wnd);};<button id="btn">click me</button>所以你的代码片段实际上只是更新你当前的文档:function myFunction() {&nbsp; window.document.write(&nbsp; &nbsp; "blank\<script\>alert(window.opener !== window)\</script\>"&nbsp; );}<button onclick="myFunction()">Try it</button>然而,奇怪的是 Firefox 确实将 更新openedWindow.opener为任何窗口将window.open()以其名称调用。这确实是一个错误,并且是最终导致您出现问题的原因,因为它应该保持原状(null在您的示例代码段中)。但请注意,您尝试执行的核心操作(获取“原始父窗口实例的引用”)在此处无关紧要,因为您的代码片段中始终只有一个 Window。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript