admin管理员组

文章数量:1302970

I have to prompt a user when he/she tries to exit the browser window. For example, when you go to GMail and you start posing a new message, and then try to close it before saving anything, GMail will give you a popup saying something like:

Do you really want to exit this page?

and then you have a choice of either leaving the page or staying on it. So what I am interested in is how they did it and what trick they used (if any) when the user presses Stay on this page.

I have to prompt a user when he/she tries to exit the browser window. For example, when you go to GMail and you start posing a new message, and then try to close it before saving anything, GMail will give you a popup saying something like:

Do you really want to exit this page?

and then you have a choice of either leaving the page or staying on it. So what I am interested in is how they did it and what trick they used (if any) when the user presses Stay on this page.

Share Improve this question edited May 2, 2014 at 1:19 Harry Johnston 36.3k6 gold badges72 silver badges165 bronze badges asked Jan 26, 2011 at 19:43 Vladimir LiVladimir Li 1512 silver badges7 bronze badges 2
  • 4 I just want to say, this can be annoying for some users. Do you really need it? Couldn't you save the info (somewhere), without having to do this? – Mateen Ulhaq Commented Jan 26, 2011 at 19:45
  • Please don't do this. Signed, all internet users. – theflowersoftime Commented Mar 20, 2014 at 17:27
Add a ment  | 

2 Answers 2

Reset to default 7

To avoid annoying users, you would probably want to have the state to be changeable, depending on if an operation is running. Something like this:

window.beforeunload = function(){
  if(isPerformingOperation) {
    return 'Are you sure you want to leave?';
  }
}

Set isPerformingOperation to true when you want to prompt them, and turn it off when you are done.

Bind a function to onbeforeunload.

window.onbeforeunload = function(){
  return 'Are you sure you want to leave?';
};

Should work in all browsers (tested in IE 8, FF 3.6, Chrome 9).

Or with jQuery:

$(window).bind('beforeunload', function(){
  return 'Are you sure you want to leave?';
});

本文标签: javascriptShow popup when user tries to exit the browser (GMail style)Stack Overflow