【问题标题】:Closing Child (popup window) when Parent window is closed关闭父窗口时关闭子窗口(弹出窗口)
【发布时间】:2014-07-13 21:10:27
【问题描述】:

我有一个简单的示例页面,当您单击链接时,我正在处理一个弹出子弹出窗口。我一直在尝试各种卸载事件来在父窗口关闭时关闭子窗口,但似乎无法弄清楚我缺少与简单编码相关的内容。

弹出窗口完美无缺,但关闭父窗口会使弹出窗口保持打开状态。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>

<a href='javascript:void(0);' onclick='window.open("http://example.com/files/foldername/","pagename","width=800, height=800");' target='windowname'><font color="#70c7c8">Link Name</a>
</body>
</html>

【问题讨论】:

    标签: javascript html parent-child


    【解决方案1】:

    您正在寻找window.onbeforeonload

    <script>
        var openPopup = function() {
            var popupWindow = window.open("http://example.com","pagename","width=800, height=800");
            window.onbeforeunload = function() {
                popupWindow.close();
            };
        }
    </script>
    <a href='javascript:void();' onclick='openPopup()'>Click to open a window...</a>
    

    http://jsfiddle.net/LM35w/

    (你不知道我关闭了多少次窗口来测试它并失去了小提琴的踪迹......)

    【讨论】:

    • LOL 哦,伙计,我可以想象整个下午都在这样做。那是我缺少的确切命令,是 window.onbeforeonload....非常感谢!
    • 嗯,Chrome 似乎对 onbeforeunload 处理程序有一种...特殊的方法:stackoverflow.com/questions/4802007/… 我不知道任何解决方法,抱歉。
    • 感谢@DanielBeck。我怀疑如何为多个子弹出窗口执行此操作。
    • @Karthiga 方式相同,只需保留对每个弹出窗口的引用并在每个弹出窗口上调用 .close()。 (但请注意,此答案已过时,可能不再有效;与 2014 年相比,现在您可以在 onbeforeunload 处理程序中执行的操作受到更多限制)
    • 是的,正如你所说,我将所有打开的窗口收集在一个数组中,并执行相同的操作,现在它工作正常。这个功能是否可以用于关闭选项卡而不是关闭窗口??
    猜你喜欢
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    相关资源
    最近更新 更多