JavaScript: Ask or confirm from user before leaving page using JavaScript.

Aman Sharma
0
Introduction:

Some time while development we face a situation to check whether user want to close page or not. So in that case we have to confirm this on closing the page or on going backward or forward.


In this article I will discuss how to confirm before leaving page. We use Javascript function to confirm this. We use window.onbeforeunload event to achieve this.

Javascript code :


<script type="text/javascript">
        var hook = true;
        window.onbeforeunload = function () {
            if (hook) {
                return "Did you save your changes?"
            }
        }
        function unhook() {
            hook = false;
        }
    </script>


Demo Application with code:



Full Code for Sample webpage:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript">
        var hook = true;
        window.onbeforeunload = function () {
            if (hook) {
                return "Did you save your stuff?"
            }
        }
        function unhook() {
            hook = false;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <center>
    <fieldset style="width:300px"><legend><strong>Confirm Before Leaving page</strong></legend>
    <div><br /><br />
        Ask User If he wants to close Page or not.
 <br /><br />
    </div></fieldset></center>
    </form>
</body>

</html>


Use the above code and check result.

Note: You can ask if you have doubt in article or other article by posting in comment area.

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !