Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(window).unload is not firing

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.

like image 234
Sergio Romero Avatar asked Feb 21 '12 21:02

Sergio Romero


2 Answers

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 every time you try to navigate away from a page sucks:

enter image description here

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.

like image 143
Darin Dimitrov Avatar answered Nov 06 '22 21:11

Darin Dimitrov


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>
like image 19
bhelm Avatar answered Nov 06 '22 21:11

bhelm