Reputation: 889
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
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
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
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