Calling JS functions on browser tab close

后端 未结 3 2038
忘掉有多难
忘掉有多难 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条回答
  •  旧时难觅i
    2020-12-07 03:54

    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.');
    });
    

提交回复
热议问题