最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Are you sure you want to navigate? - Stack Overflow

programmeradmin0浏览0评论

What is the JavaScript code/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?"

What is the JavaScript code/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?"
Share Improve this question asked Feb 25, 2010 at 2:24 Phillip SennPhillip Senn 47.7k91 gold badges261 silver badges378 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

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)

  1. 暂无评论