aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/api/beforeunloadevent/index.html
blob: f85b0e60a4372ee564da418338cd6347f46409ee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
---
title: BeforeUnloadEvent
slug: Web/API/BeforeUnloadEvent
tags:
  - API
  - BeforeUnloadEvent
  - 参考
translation_of: Web/API/BeforeUnloadEvent
---
<p>{{APIRef}}</p>

<p><strong><code>beforeunload</code></strong> 事件触发于 window、document 和它们的资源即将卸载时。 </p>

<p>当事件属性 <code>returnValue</code> 被赋值为非空字符串时,会弹出一个对话框,让用户确认是否离开页面(示例如下)。否则,事件被静默处理。一些浏览器实现仅在框架或内置框架接收到用户手势或交互时才显示对话框。在 <a href="#浏览器兼容性">浏览器兼容性</a> 中查看更多信息。</p>

<table class="properties">
 <tbody>
  <tr>
   <td>Bubbles</td>
   <td>No</td>
  </tr>
  <tr>
   <td>Cancelable</td>
   <td>Yes</td>
  </tr>
  <tr>
   <td>Target objects</td>
   <td>defaultView</td>
  </tr>
  <tr>
   <td>Interface</td>
   <td>{{domxref("Event")}}</td>
  </tr>
 </tbody>
</table>

<h2 id="示例">示例</h2>

<pre class="brush:js;">window.addEventListener("beforeunload", function( event ) {
  event.returnValue = "\o/";
});

//等同于
window.addEventListener("beforeunload", function( event ) {
  event.preventDefault();
});
</pre>

<p>基于 Webkit 的浏览器没有遵循该弹窗规范。以下是一个基本跨浏览器运行的例子。</p>

<pre class="brush: js">window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";

  (e || window.event).returnValue = confirmationMessage;     //Gecko + IE
  return confirmationMessage;                                //Webkit, Safari, Chrome etc.
});</pre>

<h2 id="浏览器兼容性">浏览器兼容性</h2>

<p>{{Compat("api.BeforeUnloadEvent")}}</p>

<h2 id="参见">参见</h2>

<ul>
 <li>{{Event("DOMContentLoaded")}}</li>
 <li>{{Event("readystatechange")}}</li>
 <li>{{Event("load")}}</li>
 <li>{{Event("beforeunload")}}</li>
 <li>{{Event("unload")}}</li>
 <li><a href="http://www.whatwg.org/specs/web-apps/current-work/#prompt-to-unload-a-document">卸载文档 — 提示卸载文档</a></li>
</ul>