Asce4s
Asce4s

Reputation: 889

How to trigger a browser window or tab close event with jQuery

Is there any way to trigger a window/tab close event with jQuery. I already tried with

$('selector').unload() 

But it didn't work.

Upvotes: 5

Views: 32718

Answers (3)

Kathir
Kathir

Reputation: 4377

In Javascript

window.onbeforeunload = function (event) {
    var message = 'Important: Please click on \'Save\' button to leave this page.';
    if (typeof event == 'undefined') {
        event = window.event;
    }
    if (event) {
        event.returnValue = message;
    }
    return message;
};

In jQuery

$(window).on('beforeunload', function(){
      return 'Are you sure you want to leave?';
});

Upvotes: 1

Dilantha
Dilantha

Reputation: 1634

Try this

$(window).unload(function() {  
        alert("Unload");  
});​

Note : some times dialogs are blocked in unload . You can check your console to make it confirm.

Upvotes: 0

Mathew Thompson
Mathew Thompson

Reputation: 56429

You can use unload() on the window property in jQuery:

$(window).unload(function() {
   //do stuff
});

You don't need jQuery to do it though, you can use good ol' fashioned JavaScript:

window.onbeforeunload = function(e){
    var msg = 'Are you sure?';
    e = e || window.event;

    if(e)
        e.returnValue = msg;

    return msg;
}

Upvotes: 10

Related Questions