关闭选项卡之前的确认框,而不是重新加载页面时的确认框

时间:2014-01-29 06:03:26

标签: javascript asp.net webforms

我的客户端要求是在我的Web应用程序的浏览器选项卡关闭时发出警告消息。可以使用JavaScript onunloadonbeforeunload事件来完成。

但是我的应用程序中有许多下拉框并选择了一些下拉框,需要重新加载页面。在此重新加载期间,每次onunloadonbeforeunload被触发并显示警报消息。我想在重新加载页面上停止触发此onunloadonbeforeunload事件,但在关闭浏览器选项卡时会显示警告消息。如果URL中有任何更改,则会有所帮助。但我的网址没有改变。

我知道这种情况没有直接的JavaScript事件支持。任何人都可以建议替代解决方案吗?

更新

<script language="JavaScript1.2" type="text/javascript">  

    var g_isPostBack = false;        
    function windowOnBeforeUnload()
    {        
        if ( g_isPostBack == true )
        return; // Let the page unload

        if ( window.event )
        window.event.returnValue = 'Are you sure?'; // IE
        else
        return 'Are you sure?'; // FX
     }
    window.onbeforeunload = windowOnBeforeUnload;    

</script>

代码背后:

protected void Page_Load(object sender, EventArgs e)
        {             
          this.ClientScript.RegisterOnSubmitStatement(this.GetType(), "OnSubmitScript", "g_isPostBack = true;");

        }

2 个答案:

答案 0 :(得分:0)

尝试以下代码,如果这是您的要求,请更新我们。

<script type="text/javascript">
    var new_var = true;
    window.onbeforeunload = function () {
        if (new_var) {
            return "you have unsaved changes, if you leave they will be lost"
        }
    }
    function unhook() {
        new_var = false;
    }
</script>

答案 1 :(得分:0)

遇到同样的问题尝试这个脚本

  <script language="JavaScript" type="text/javascript">
        window.onbeforeunload = confirmExit;
        function confirmExit() {
            return "You are about to exit the system before freezing your declaration! If you leave now and never return to freeze your declaration; then they will not go into effect and you may lose tax deduction, Are you sure you want to leave now?";
        }
        $(function() {
            $("a").click(function() {
                window.onbeforeunload = null;
            });
            $("input").click(function() {
                window.onbeforeunload = null;
            });
        });
    </script>