Calling JS functions on browser tab close Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Calling JS functions on browser tab close without wasting too much if your time.

The question is published on by Tutorial Guruji team.

enter image description hereI need to call a JS 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 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");
 });

its not working. can anyone answer for this. is there any other js 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 also when i used that. can anybody suggest something. Thanks.

Answer

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.

We are here to answer your question about Calling JS functions on browser tab close - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji