$(window).unload is not firing

流过昼夜 提交于 2019-11-26 09:58:36

问题


I want to execute an action method when the user is abandoning a particular page using jQuery.

The page has the following code:

    <script type=\"text/javascript\">

        $(window).unload(function () {
            alert(\"Handler for .unload() was called.\");
        });

    </script>

When I navigate away from the page I never see the expected alert.


回答1:


Actually some browsers such as Google Chrome might block if you attempt to alert in a window unload. As a user I like this feature. Alerting everytime you try to navigate away from a page sucks:

Replace the alert with a console.log or something else less intrusive to the user and the event will be happily called.

You might also want to checkout the onbeforeunload event.




回答2:


jquery .on('unload',..); was not reliable working for me. i switched over to use beforeunload. just make sure you are not returning anything, or the user will get a "are you sure to leave the page"-popup.

<script type='text/javascript'>
    $(window).on('beforeunload', function(){
         console.log("beforeUnload event!");
     });
</script>



回答3:


as bhelm said beforeunload works for me as well.
return false on this event will invoke the browser default

are you sure you want to leave this page?


$(window).on('beforeunload', function ()
    {
        return false;
    });



回答4:


window.onbeforeunload=navigationError;

var dont_confirm_leave = 0; var leave_message = 'You sure you want to leave?';

function navigationError(e) 
  {
    if(dont_confirm_leave!==1)
    {
      if(!e) e = window.event;
      //e.cancelBubble is supported by IE - this will kill the bubbling process.
      e.cancelBubble = true;
      e.returnValue = leave_message;
      //e.stopPropagation works in Firefox.
      if (e.stopPropagation) 
      {
        e.stopPropagation();
        e.preventDefault();
      }

      //return works for Chrome and Safari
      return leave_message;
    }
  }



回答5:


if you want to alert user that you leaving this page then if this

/* $(window).unload(function()
{
	//alert("you leaving this page");
	console.log("you leaving this page");
}); */

function not work for you then replace your code with on("beforeunload",function) like this

$(window).on("beforeunload", function()
{
	alert("you leaving this page");
	console.log("you leaving this page");
});

this work for me ! you can see the output in console log you leaving this page



来源:https://stackoverflow.com/questions/9385778/window-unload-is-not-firing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!