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.

2

3 Answers 3

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;
}
2
  • 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, 2013 at 11:55
  • 3
    It will also called when user navigate to some other page rather than closing the window Sep 24, 2013 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?';
});
1
  • 1
    It works including page refresh, I need specifically for tab close or browser close
    – sam ruben
    Sep 17, 2019 at 13:38
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.

1
  • 1
    What if person is not closing browser but navigating to some other page. unload will also run in that condition. Sep 24, 2013 at 12:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.