I want to call function on window unload

12,668

Solution 1

You can't prevent unload to stop the page from unloading. You need to bind to onbeforeunload instead. You should just return the string you want to display to the user from the event handler (note that in some browsers the string may not be displayed)

<script type="text/javascript">
    window.onbeforeunload = function(e){
        var msg = 'Are you sure?';
        e = e || window.event;

        if(e)
            e.returnValue = msg;

        return msg;
    }
</script>

More info here

JSFiddle Example here

Solution 2

change your code to this to make it work cross-browser:

<script>
  window.onbeforeunload = function (e) {
    e = e || window.event;

    // For IE and Firefox prior to version 4
    if (e) {
      e.returnValue = 'Do you really want to exit?';
    }

    // For Safari
    return 'Do you really want to exit?';
  };
</script>
<body>
...

note that this is using the onbeforeunload-event (more information / view an example) where the return-value has to be the message that should be shown to the user.

i don't know if you'll have a chance to react on the confirmation to do something after that (closing child-windows for example), but i don't think so.

Share:
12,668
Tushar Ahirrao
Author by

Tushar Ahirrao

I know Javascript, HTML5, CSS3, Java, PHP and more.... I enjoy building things, learning programming languages, listening to music.

Updated on June 04, 2022

Comments

  • Tushar Ahirrao
    Tushar Ahirrao almost 2 years

    I am trying to display confirmation box using window.confirm on window unload event,

    and if user click on OK button on confirmation box then i want to call one function and if user click CANCEL button then window should be get close.

    My code is :

    <script>
            function confirmit(){
                    var result=window.confirm("Are you sure?");
                    if(result) {
                        // close all child windows
                    } else{
                        // window should not get close
                    }
                }
    </script>
    <body onunload='confirmit();' >
    

    But the problem is if i click on CANCEL button, window is getting close.

    Please help me.

    Thanks