javascript 我想在窗口卸载时调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7412681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:02:33  来源:igfitidea点击:

I want to call function on window unload

javascriptjqueryhtmleventsjavascript-events

提问by Tushar Ahirrao

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

我正在尝试在窗口卸载事件上使用 window.confirm 显示确认框,

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

谢谢

回答by Paul

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)

您无法阻止卸载以阻止页面卸载。您需要绑定到 onbeforeunload 。您应该只从事件处理程序返回您想要显示给用户的字符串(请注意,在某些浏览器中可能不会显示该字符串)

<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

JSFiddle示例在这里

回答by oezi

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.

请注意,这是使用onbeforeunload-event更多信息/查看示例),其中返回值必须是应显示给用户的消息。

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.

我不知道你是否有机会在确认之后做出反应(例如关闭子窗口),但我不这么认为。