user1960836
user1960836

Reputation: 1782

Javascript confirm method

I have added a confirm box that works when user refreshes page, and when user tries to navigate away from the current page. But I want it to do so that it cancels the operation of going away from the page. I'm not sure how to implement this.

Another problem that I have, is that this code only works in EI, and not in Firefox or Chrome. Normally it is the other way round. But maybe I should post the browser issue as a separate post?

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>Verify</title>       
        <script type="text/javascript">
            function handleRequest() {
                if(confirm('Sure you want to quit?')) {
                //  redirect or quit;
                } else {
                    //Do not change page or quit 
                }
            }
        </script>

    <body onunload="handleRequest()">

        <p></p>
        <p>Body content</p>
    </body>

</html>

Upvotes: 0

Views: 74

Answers (2)

Sebastien C.
Sebastien C.

Reputation: 4833

You can only cancel it with onbeforeunload, and by returning false to the event :

<body onbeforeunload="return confirm('Sure you want to quit?');">

Upvotes: 1

Alex
Alex

Reputation: 11245

Use onbeforeunload:

window.onbeforeunload = function(e) {
  return 'Dialog text here.';
};

It will open dialogbox and ask user stay or go away from page. It's native browser behavior.

Upvotes: 2

Related Questions