javascript – Getting Close event of another (programmatically opened) browser window-ThrowExceptions

Exception or error:

I am opening a new browser window on a click event. Is there a way that bound the close event of the child window from the parent

Sample html:

<button id="btn">Click</button>
<label id="lbl"></label>

Script:

$(function () {
    $("#btn").on('click', function () {
        window.open("about:blank", "test", "height=200px,width=200px");
        $("#lbl").html("Opend");
    });
});

Lest say for example, I want to change the label text to closed when the child is closed.

Js Fiddle Link

How to solve:

Use onbeforeunload event:

var new_window = window.open("about:blank", "test", "height=200px,width=200px");
new_window.onbeforeunload = function () {
    alert('closed');
}

Demo: https://jsfiddle.net/p48eu9ng/1/

###

try this

$(function(){

    $("#btn").on('click',function(){

       var new_window = window.open("about:blank","test","height=200px,width=200px");
        new_window.onbeforeunload = function(){ $("#lbl").html("Closed");}
        $("#lbl").html("Opend");
    });

});

###

Try this fiddle, changing label to close after closing new window.

$(function(){

    $("#btn").on('click',function(){        
    var newWindow = window.open("about:blank","test","height=200px,width=200px");
        $("#lbl").html("Opend");        
    $(newWindow).bind("beforeunload", function() { 
        $("#lbl").html("Closed");
    })    
    }); 

Leave a Reply

Your email address will not be published. Required fields are marked *