Why is OnBeforeUnload firing twice with asp:LinkButton?

非 Y 不嫁゛ 提交于 2019-12-12 08:16:18

问题


I have the following Jquery function to notify the user with a prompt when they have unsaved changes (similar to how SO does it) and are trying to leave the current screen.

<!-- in my aspx page -->
<script type="text/javascript" language="javascript">
    window.onbeforeunload = function()
    {
        if (HasPendingUpdates())
        {
            return "Changes you have made will not be saved.";
        }
    }
</script>

This works as expected and shows the message box when the user tries to click a href to browse away or use the back button etc. The problem I am having is that one of my links is a asp:LinkButton because it needs to fire off some server side code before leaving the page. When the user clicks this LinkButton they get the prompt twice.

Scenarios:

  1. User clicks the LinkButton
  2. Prompt appears and user clicks the cancel button.
  3. Prompt disappears and user is still on screen. GOOD.

  4. User clicks the LinkButton

  5. Prompt appears and clicks the OK button.
  6. Prompt disappears and the same prompt shows again.
  7. User clicks OK again.
  8. Prompt disappears and user moves to the next screen and all is good.

So why am I getting the second prompt??? How is the OnBeforeUnload firing twice?


回答1:


I had a similar problem, however, I didn't want to fire onbeforeunload for LinkButtons at all, therefore I used the following for every LinkButton on the .aspx page:

OnClientClick="eval(this.href);return false"

Functionality of the LinkButtons wasn't crippled, since all they did was supplying a Command with CommandArgument for the codebehind to handle...




回答2:


Adding handlers with jQuery stacks them. If you're assigning a handler with some jQuery function for your hrefs and then assigning it again for your linkbutton, there will be two handlers in place.

Check how often you are binding the onunload handler, and make sure that you're either unbinding previous handlers or only doing it once.




回答3:


Here is how to fix this:

    var checkChangesEnabled = true;
    window.onbeforeunload = confirmExit;

    function confirmExit() {
        if (checkChangesEnabled) {
            event.returnValue = "Changes you have made will not be saved.";
            disableCheck();
        }
    }

    function disableCheck() {
        checkChangesEnabled = false;
        setTimeout("enableCheck()", "100");
    }

    function enableCheck() {
        checkChangesEnabled = true;
    } 


来源:https://stackoverflow.com/questions/2239456/why-is-onbeforeunload-firing-twice-with-asplinkbutton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!