使用Javascript从父onblur关闭子窗口

Close Child Window from Parent onblur using Javascript

本文关键字:窗口 onblur Javascript 从父 使用      更新时间:2024-04-25

我有一段代码,它在弹出窗口(子窗口)中返回一些其他页面(谷歌)。我不能在子窗口中编写任何代码,所以我必须从父窗口完成所有操作。我正在尝试将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>

跳过.close() 后面的括号

newWin.onblur = newWin.close;

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

另一个答案如下:

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();
                };
            }

除了上面的这个,没有其他解决方案对我有效。

谨致问候,Shoaib。

我得到了解决方案。

使用"window.top.close();"

上述解决方案将不再适用于跨源域,可能会引发此错误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()
 })