这篇翻译不完整。请帮忙从英语翻译这篇文章。
当浏览器窗口,文档或其资源将要卸载时,会触发beforeunload事件。
如果处理函数为Event对象的returnValue属性赋值非空字符串,浏览器会弹出一个对话框,来询问用户是否确定要离开当前页面(如下示例)。没有赋值时,该事件不做任何响应。
概述
- Specification
- HTML5
- Interface
- Event
- Bubbles
- No
- Cancelable
- Yes
- Target
- defaultView
- Default Action
- Varies (提示用户是否确认离开当前页面).
属性
| Property | Type | Description |
|---|---|---|
target 只读 |
EventTarget |
The event target (the topmost target in the DOM tree). |
type 只读 |
DOMString |
The type of event. |
bubbles 只读 |
boolean |
Does the event normally bubble? |
cancelable 只读 |
boolean |
Is it possible to cancel the event? |
returnValue |
DOMString |
当前事件的返回值,The current return value of the event (即显示给用户的提示信息). |
示例
window.addEventListener("beforeunload", function (event) {
event.returnValue = "\o/";
});
// 等价于
window.addEventListener("beforeunload", function (event) {
event.preventDefault();
});
基于WebKit内核的浏览器在弹出提示框时未遵循该规范。跨浏览器可运行的示例,代码基本如下:
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
(e || window.event).returnValue = confirmationMessage; // Gecko and Trident
return confirmationMessage; // Gecko and WebKit
});
注意
该事件处理函数在返回非空值,会提示用户是否关闭页面。在多数浏览器中,返回值会显示在提示框中。Firefox4以及之后版本的浏览器不会向用户显示返回的字符串。取而代之的是,Firefox会展示字符串“This page is asking you to confirm that you want to leave - data you have entered may not be saved”。参见bug 588292。
从2011年5月25号开始,HTML5规范指出在此事件处理函数中,对于window.alert(), window.confirm(), 和 window.prompt() 的调用会被忽略。详见HTML5规范说明。
同样需要注意的是许多手机浏览器会忽略该事件处理的返回值(亦即,它们不会要求用户确认,而是直接执行操作)Firefox在about:config中有一个隐藏的设置来做同样的事。其实就是用户确认文档总会被卸载。