Close all child windows when parent window is closed
use this
var popup = window.open("popup.html", "popup", "width=200,height=200");
window.onunload = function() {
if (popup && !popup.closed) {
popup.close();
}
};
If you open all child windows with window.open, include this javascript in all pages, then CloseAll(false); from any included page will close all child, grandchildren, great-grand... etc., and redirect the first (root) page to login.aspx, and will not interfere with any event triggers because it pases the intial handler through.
function CloseAll(bTopFound)
{
if (!bTopFound && nParent != null && !nParent.closed) {
//parent window was not closed
nParent.CloseAll(false);
return;
} else {
if (nParent == null || nParent.closed)
{
top.location = '/login.aspx';
}
}
for (var i = 0; i < Windows.length; i++)
{
if (!Windows[i].closed) {
Windows[i].CloseAll(true);
}
}
nParent = null;
setTimeout(window.close, 150);
}
var Windows = [];
//override window.open to inject store child window objects
window.open = function (open) {
return function (url, name, features) {
// set name if missing here
name = name || "default_window_name";
var newWindow = open.call(window, url, name, features);
Windows.push(newWindow);
return newWindow;
};
}(window.open);
var nParent = null;
window.onload = function (load) {
return function (e) {
nParent = window.opener;
if (load != null) {
load.call(e);
}
}
}(window.onload);
window.onunload = function (unload) {
return function (e) {
//promote first branch page to parent
if (nParent != null && !nParent.closed && Windows.length > 0) {
nParent.Windows.push(Windows[0]);
Windows[0].nParent = nParent;
}
//make first child window new root
for (var i = 1; i < Windows.length; i++) {
Windows[i].nParent = Windows[0];
Windows[0].Windows.push(Windows[i]);
}
if (unload != null) {
unload.call(e);
}
}
}(window.onunload);
Found a proper solution (jQuery) that works in the lastest versions of Chrome, Firefox and IE.
Initially wanted to use jQuery $().unload()
function (http://api.jquery.com/unload/) but it's deprecated since 1.8 (http://bugs.jquery.com/ticket/11733). Since $().unload()
is the shortcut for $().bind('unload', fn)
, I tried to use the basic one and it worked.
$(window).on('unload', function() {
closeAll();
});