Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
46
rated 0 times [  50] [ 4]  / answers: 1 / hits: 24046  / 11 Years ago, wed, july 31, 2013, 12:00:00

enter


I need to call a Javascript function when user closing the browser tab. The problem is I want to happen this only when user closing the browser. No need to happen for page refresh, link navigation,form submit and back button press. I have tried the below JQuery code so far.


$(window).bind(
"beforeunload",
function() {
alert("don't close me");
return false;
}
)
$('form').submit(function() {
jQuery(window).unbind("beforeunload");
});

It's not working. Is there any other Javascript tools than JQuery available for this?


And if I call my function "beforeunload" event, above message is coming. I don't want to show this message and my function has to be worked. I tried by giving e.preventDefault. But it's not calling my function again. Can anybody suggest something.


Thanks.


More From » jquery

 Answers
2

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.


[#76622] Tuesday, July 30, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daytonm

Total Points: 519
Total Questions: 83
Total Answers: 89

Location: Saudi Arabia
Member since Mon, Sep 5, 2022
2 Years ago
;