0

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.

<html>
<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;
        window.onbeforeunload = goodBye;

        </script>

  </body>
</html>
  • whats the error you are getting in developer console? make sure that its not blocked by some extensions in browser. – Dineshkumar Nov 29 '15 at 05:45
  • 2
    With `onbeforeunload`, this is defined behavior. "[... the HTML5 specification states that calls to `window.alert()`, `window.confirm()`, and `window.prompt()` methods may be ignored during this event.](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#Notes)" The event expects a message to be `return`ed rather than `alert`ed explicitly. – Jonathan Lonowski Nov 29 '15 at 05:45
  • Possible duplicate of [Javascript onload and onunload](http://stackoverflow.com/questions/9907867/javascript-onload-and-onunload) – ForguesR Nov 29 '15 at 05:54

1 Answers1

0

try this

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

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

    window.onunload = goodBye;
    window.onbeforeunload = goodBye;

    </script>
    <a href="http://stackoverflow.com/">stackoverflow</a>

huabing
  • 36
  • 3