Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 55 期(W3C 标准-JavaScript-事件):页面卸载事件 beforeunload #58

Open
wingmeng opened this issue Jul 9, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented Jul 9, 2019

在某些内容项较多的表单页面,为防止用户误操作离开页面导致输入内容丢失,一般会在该页面刷新、关闭或跳转时弹出一个确认提示框(如下图):

image

用户可以选择“取消”而继续留在当前页面。想要实现这个功能,需要用到 beforeunload 事件,它会在页面卸载前触发。

window.addEventListener('beforeunload', function(e) {
  var msg = '你真的要走啊?';
  
  (e || window.event).returnValue = msg;  // Gecko and Trident
  return msg;  // Gecko and WebKit
});

需要注意的是,除了 IE 外,Chrome 和 Firefox 浏览器都不会显示自定义的提示语(上面 msg 定义的文案),只要 returnValue 赋值为非空字符串,浏览器就会弹出一个对话框,如果没有赋值,该事件不作任何响应。

beforeunload

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant