5

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

$('selector').unload() 

But it didn't work.

SexyBeast
  • 7,913
  • 28
  • 108
  • 196
Asce4s
  • 819
  • 3
  • 10
  • 16

3 Answers3

10

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;
}
Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
  • 1
    java script method worked. thanks but I need something like this $(window).unload(function() { window.location='clearsession.php' }); How can I do it with js – Asce4s Jul 24 '13 at 11:55
  • 3
    It will also called when user navigate to some other page rather than closing the window – Jitendra Pancholi Sep 24 '13 at 12:10
1

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?';
});
Kathir
  • 4,359
  • 3
  • 17
  • 29
0

Try this

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

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

Dilantha
  • 1,552
  • 2
  • 30
  • 46