I need to call a JS function when user closing the browser tab. the problem is i want t
onunload (or onbeforeunload) cannot redirect the user to another page. This is for security reasons.
If you want to show a prompt before the user leaves the page, use onbeforeunload:
window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
Or with jQuery:
$(window).bind('beforeunload', function(){
return 'Are you sure you want to leave?';
});
This will just ask the user if they want to leave the page or not, you cannot redirect them if they select to stay on the page. If they select to leave, the browser will go where they told it to go.
You can use onunload to do stuff before the page is unloaded, but you cannot redirect from there (Chrome 14+ blocks alerts inside onunload):
window.onunload = function() {
alert('Bye.');
}
Or with jQuery:
$(window).unload(function(){
alert('Bye.');
});
JSFiddle uses the following to alert the user they are trying to close their modified fiddle without saving:
window.onbeforeunload = function(){
if (window.editorsModified){
return "You've modified your fiddle, reloading the page will reset all changes."
}
};
This works reliably (http://jsfiddle.net/MaxPRafferty/b6uEF/show/ ,Latest Chrome, FF, IE10 ), but will always prompt the user. You can't force the page open by returning false;
I agree with the comments that this is a bad practice, but I can't resist the call to attempt answering the question.
The only way I can think of to accomplish this is to use onbeforeunload, which you're already doing. But you need a way of disabling that alert when someone navigates away from the page by some other means.
var show_close_alert = true;
$("a").bind("mouseup", function() {
show_close_alert = false;
});
$("form").bind("submit", function() {
show_close_alert = false;
});
$(window).bind("beforeunload", function() {
if (show_close_alert) {
return "Killing me won't bring her back...";
}
});
It's not foolproof, as in there are ways to close the browser without seeing the alert (like clicking a link, hitting Stop immediately, and then closing the browser), but it may be as close as you can get.
Here's a fiddle.
But please... don't do this.