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

10,198

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.

Share:
10,198
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    Admin almost 2 years

    How to close the child window when closing parent window in javascript?