简体   繁体   English

onunload和onbeforeunload无法正常工作

[英]onunload and onbeforeunload not working

I have this script in my aspx page 我的aspx页面中有此脚本

<script language="JavaScript" type="text/javascript">     
    window.onbeforeunload = function(e) {
        return 'Bye now!';
    }; 
</script>

But this is not invoked when I close the browser. 但这在我关闭浏览器时不会被调用。 I need to pop an alert asking the user to confirm. 我需要弹出一个警报,要求用户确认。 I need to do this in the aspx page using javascript. 我需要使用JavaScript在aspx页面中执行此操作。 The browser I tried was mozilla firefox. 我尝试的浏览器是mozilla firefox。 Thanks 谢谢

The following code should fix your issue: 以下代码可以解决您的问题:

(function () {
    window.unloader = function(e) {
       (e || window.event).returnValue = null;
       return null;
    };
    window.addEventListener("beforeunload", window.unloader);
})();

You are not going to be able to specify a message, it is defaulted by the browser. 您将无法指定消息,浏览器默认为该消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM