5

I have a simple sample page that I'm working on with a popup child popup window when you click on a link. I've been trying various unload events to close the child window when the parent is closed but cannot seem to figure out what I'm missing that ties into the simple coding.

The popup works flawlessly, however closing the parent window leaves the popup open.

<!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>
user3518979
  • 77
  • 2
  • 7

1 Answers1

10

You're looking for 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/

(You have no idea how many times I closed the window to test it and lost track of the fiddle...)

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
  • LOL Oh man, I can imagine have been doing that all afternoon. That was the exact command I was missing, was the window.onbeforeonload....Thank you SO much! – user3518979 Jul 13 '14 at 22:01
  • Hm, it does appear that Chrome has an... idiosyncratic approach to the onbeforeunload handler: http://stackoverflow.com/questions/4802007/window-onbeforeunload-not-working-in-chrome I don't know of any workaround for this, sorry. – Daniel Beck Jul 06 '15 at 17:20
  • thanks @DanielBeck . i have an doubt how to do this for multiple child popups. – Karthiga Jan 22 '19 at 11:00
  • @Karthiga it'd be the same way, just keep a reference to each of the popups and call `.close()` on each of them. (But note that this answer is outdated and may no longer work; there are more restrictions on what you can do in an `onbeforeunload` handler now than there were in 2014) – Daniel Beck Jan 22 '19 at 21:14
  • yeah as you said i collected all opening windows in an array and do the same operation and its working fine now. By any chance dooes this function works for closing the tab instead of closing the window ?? – Karthiga Jan 23 '19 at 05:25
  • For these purposes tabs and windows are the same thing. – Daniel Beck Jan 23 '19 at 13:10