views:

36

answers:

1

Hi friends, how to close the child window when closing parent window in javascript?

Thanks in advance.

A: 

If by parent and child windows you mean a pop-up window and the window that opened it, you can't do exactly this, but the following script in the main window will close the pop-up window when the main window is unloaded (i.e. either closed or the user navigates to another page or refreshes):

var popUp = window.open("popup.html", "popup", "width=300,height=200");

window.onunload = function() {
    if (popUp && !popUp.closed) {
        popUp.close();
    }
};

Historical note: it used to be possible to do this in some browsers (e.g. Firefox) by using the dependent window property in the third parameter of the window.open call (e.g. var popUp = window.open("popup.html", "popup", "width=300,height=200,dependent");) but according to quirksmode it's no longer supported in anything. I haven't tested this myself.

Tim Down