Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 297
Asce4s Avatar asked Jul 24 '13 10:07

Asce4s


1 Answers

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;
}
like image 81
mattytommo Avatar answered Nov 01 '22 16:11

mattytommo