javascript 阻止页面跳转 onbeforeunload

在AJAX应用程序中,我们常需要在后台使用AJAX异步做很多操作。在这些操作结束之前,所有的页面跳转,都可能会导致用户的数据没有保存下来。还好,针对于Chrome/Firefox/IE7-9+,我们有:
引用:http://stackoverflow.com/questions/1299452/how-do-i-stop-a-page-from-unloading-navigating-away-in-js

var warning = true;
window.onbeforeunload = function() {
  if (warning) {
    return 'You have made changes on this page that you have not yet confirmed. If you navigate away from this page you will loose your unsaved changes';
  }
}

这段代码在Firefox下运行的结果与IE/Chrome有些不同,在FF下,我们return 的字符串不会被显示,FF会根据当前的用户浏览器语言弹出类似的对话框。

以下是截图:
Chrome/FF/IE(IE9 控制台模拟IE7-8):

1 thought on “javascript 阻止页面跳转 onbeforeunload”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.