Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

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

Copy link
Copy link
@wingmeng

Description

@wingmeng
Issue body actions

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

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.