开发者

I want to call function on window unload

I am trying to display confirmation box using wi开发者_运维问答ndow.confirm on window unload event.

If a user clicks on the OK button on confirmation box then I want to call one function and if user clicks the CANCEL button then window should be get closed.

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 closed.

Please help me.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜