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,303
  • 27
  • 100
  • 185
Asce4s
  • 689
  • 2
  • 8
  • 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;
}
mattytommo
  • 54,375
  • 15
  • 123
  • 144
  • 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
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,422
  • 2
  • 27
  • 41
0

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,219
  • 3
  • 16
  • 29