Calling JS functions on browser tab close

后端 未结 3 2040
忘掉有多难
忘掉有多难 2020-12-07 03:10

\"enterI need to call a JS function when user closing the browser tab. the problem is i want t

3条回答
  •  没有蜡笔的小新
    2020-12-07 04:06

    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.

提交回复
热议问题