Create an array to track the open windows.
Whenever you open a window, pass the handle to that window to a function that will add it to the array. When you want to close all the windows, loop through the array and close them. You don't need to worry if a child window is closed or not. The following code was quickly tested on IE 6 and FF 2. The closeWindows function would need to be called in the onunload event.
Code:
<html>
<head></head>
<body>
<script>
//The openWindow array will hold the handles of all open child windows
var openWindow = new Array();
//Track open adds the new child window handle to the array.
function trackOpen(winName) {
openWindow[openWindow.length]=winName;
}
//loop over all known child windows and try to close them. No error is
//thrown if a child window(s) was already closed.
function closeWindows() {
var openCount = openWindow.length;
for(r=0;r<openCount;r++) {
openWindow[r].close();
}
}
//Open a new child window and add it to the tracker.
function open1() {
var win1 = open("http://www.yahoo.com");
trackOpen(win1);
}
//Open a different child window and add it to the tracker.
function open2() {
var win2 = open("http://www.google.com");
trackOpen(win2);
}
//Open whatever the user enters and add it to the tracker
function open3() {
var newURL = document.getElementById("url").value;
var win3=open(newURL);
trackOpen(win3);
}
</script>
<input type="button" value="Open 1" onclick="open1()"><br>
<input type="button" value="Open 2" onclick="open2()"><br>
URL: <input type="text" id="url"> <input type="button" value="Open URL" onclick="open3()"><br>
<input type="button" value="Close All" onclick="closeWindows()">
</body>
</html>
Hope this helps.