Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Consider the following HTML snippet containing some javascript utilizing prompt and unload. The prompt() method works fine but I want alerting something like Goodbye, user when reloading or leaving the page. Any help is greatly appreciated.

<body onload="promptName()" >


        <script type="text/javascript">
        function promptName()
        {
            var userName = prompt("What's your name ?", "")
            return userName;
        }

        function goodBye()
        {
            alert("Goodbye, " + promptName() + "!");
        }

        window.onunload = goodBye();

        </script>

  </body>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
440 views
Welcome To Ask or Share your Answers For Others

1 Answer

You should write it like this:

window.onunload = goodBye;

Also, you might consider using the onbeforeunload event in some browsers:

window.onbeforeunload = goodBye;

When you write window.onunload = goodBye(); you assign whatever handler that is returned from goodBye to the unload event. Since nothing is returned, there will be no event handler. You need to reference the function instead: window.onunload = goodBye;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...