开发者

Are you sure you want to navigate?

开发者 https://www.devze.com 2022-12-21 17:18 出处:网络
What is the JavaScript code/开发者_JAVA技巧event(s) that is used by sites like stackoverflow and Gmail to test for the user exiting the page once they have begun editing and try to navigate away?

What is the JavaScript code/开发者_JAVA技巧event(s) that is used by sites like stackoverflow and Gmail to test for the user exiting the page once they have begun editing and try to navigate away?

"Are you sure you want to navigate away from this page?"


The event used is called onbeforeunload.

<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
</head>
<body>
    <input id="foo"></input>

    <script type="text/javascript">
        function unloadMessage() {
            return "Are you sure you want to leave?";
        }

        function setConfirmUnload(enabled) {
            window.onbeforeunload = enabled ? unloadMessage : null;
        }

        $(document).ready(function() {
            $("#foo").keypress(function() {
                setConfirmUnload(true);
            });
        });
    </script>
</body>
</html>


onbeforeunload event. Mozilla provides useful example code. you just want to have a function that:

  1. Returns a string
  2. Sets e.returnValue to that string, where e is the argument or window.event.

The string will be used as your custom message.

0

精彩评论

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

关注公众号