admin管理员组

文章数量:1430235

I want to know how can I display a confirmation box when the users try to get out of the page, like this one here in StackOverflow when you try to close the "Ask Question" page.

Thanks you in advance.

I want to know how can I display a confirmation box when the users try to get out of the page, like this one here in StackOverflow when you try to close the "Ask Question" page.

Thanks you in advance.

Share Improve this question asked Jan 19, 2010 at 5:27 Bernardo AmorimBernardo Amorim 3432 silver badges6 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 6

Actually, all that is necessary is this:

window.onbeforeunload = function(){ return "You should save your stuff."; }

This is also kind of a dupe of this: How to show the "Are you sure you want to navigate away from this page?" when changes mitted?

In javascript, attach a function to window.onbeforeunload, like so:

window.unbeforeunload = function (e)
{
    // return (prompt ('Are you sure you want to exit?'));

    // EDIT: Amended version below: 
    var e = e || window.event;
    if (e) e.returnValue = 'Your exit prompt';
    return 'Your exit prompt';
}

EDIT: As the ments below indicate, I had misunderstood the working of the event. It should now work as intended.

Ref: window.onbeforeunload (MDC)

probably a dupe: How do you prevent a webpage from navigating away in JavaScript?, but you can do this by adding an delegate to the window.onbeforeunload event

<script type="text/javascript">
   window.onbeforeunload = function() {
      //will show a dialog asking the user if 
      //they want to navigate away from the current page
      // ok will cause the navigation to continue, 
      // cancel will cause the user to remain on the current page
      return "Use this text to direct the user to take action.";
   }
</script>

Update: doh! updated code to do what the OP really wanted :D

You want to catch the onbeforeunload event of window. Then if you return a string, the browser will display your message in a prompt. Here's an article with sample code.

You can use the window.onbeforeunload event to catch this. If there is any value inside the textarea then an alert message is shown.

That's browser based.

As long as you implement <form> tag, and you type in something in the form, and in Google Chrome, it will prompt you that message.

本文标签: YesNo box in Javascript like this one here in StackOverflowStack Overflow