最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Show popup when user tries to exit the browser (GMail style) - Stack Overflow

programmeradmin1浏览0评论

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?';
});
发布评论

评论列表(0)

  1. 暂无评论