【问题标题】:Close Child Window from Parent onblur using Javascript使用 Javascript 从父 onblur 关闭子窗口
【发布时间】:2012-07-27 12:02:13
【问题描述】:

我有在弹出(子)窗口中返回其他页面(Google)的代码。我不能在子窗口中编写任何代码,所以我必须从父窗口做所有事情。我正在尝试将 onblur 事件从父窗口绑定到子窗口,以便子窗口一旦失去焦点就应该关闭。但是,子窗口会飞溅一微秒并自动关闭。

我无法在我工作的环境中使用 jQuery。

这是我的示例代码:

<html>
<head>
</head>

<body>
<input type="button" value="Open Google" onclick="OpenWindow()" />

<script type="text/javascript">

function OpenWindow()
{
    var url="http://www.google.com";

    var newWin=window.open(url, 'Popup','height=500,width=600,left=100,top=100,resizable=yes,scrollbars=no,toolbar=no,status=no');
    newWin.focus();
    newWin.onblur =  newWin.close();    
}
</script>

</body>
</html>

【问题讨论】:

    标签: javascript window onblur


    【解决方案1】:

    跳过.close()后面的括号

    newWin.onblur = newWin.close;
    

    你想传递一个函数引用,你不想分配通过执行.close()返回的值。

    【讨论】:

      【解决方案2】:

      另一个答案可以是:

      function open_popup() {
                      var my_window = window.open("", 'targetWindow', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=750px,height=500px');
                      var html = '';
                      html = "Muhammad Shoaib Qureshi's New Window Text";
                      my_window.document.write(html);
                      my_window.focus();
                      my_window.onblur = function() {
                          my_window.close();
                      };
                  }
      

      除了上述解决方案之外,没有其他解决方案对我有用。

      问候, 肖伊布。

      【讨论】:

        【解决方案3】:

        我找到了解决方案。

        使用“window.top.close();”

        【讨论】:

          【解决方案4】:

          上述解决方案将不再适用于跨域域并且可能抛出此错误 Blocked a frame with origin "https://example.com" from accessing a cross-origin frame.

          要解决这个问题,我们可以向父窗口添加一个事件监听器并监听focus 事件,这应该在用户从生成的子窗口单击回到主窗口后触发,然后我们可以关闭框架。

           let url = "https://example.com";
           let frame = window.open(url, "Popup", "height=500,width=600,left=100,top=100,resizable=yes,scrollbars=no,toolbar=no,status=no");
           window.addEventListener('focus', (e) => {
               if (!frame.closed) frame.close()
           })
          

          【讨论】:

            猜你喜欢
            • 2013-02-14
            • 2020-10-17
            • 1970-01-01
            • 2023-03-07
            • 2017-02-08
            • 1970-01-01
            • 2012-12-15
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多