父窗口关闭时关闭子窗口(弹出窗口)

时间:2014-07-13 21:10:28

标签: javascript html parent-child

我有一个简单的示例页面,当您单击链接时,我正在使用弹出子弹出窗口。当父母关闭时,我一直在尝试各种卸载事件来关闭子窗口,但似乎无法弄清楚我错过了什么与简单编码有关。

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

<!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>

1 个答案:

答案 0 :(得分:6)

您正在寻找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/

(你不知道我多少次关闭窗户来测试它并且丢失了小提琴的轨迹......)