WindowEventHandlers.onbeforeunload

翻譯不完整。請協助 翻譯此英文文件

 

WindowEventHandlers.onbeforeunload 事件处理函数包含的代码将在 beforeunload 发出时被执行。当 window 准备释放它的资源时,该事件被触发。此时 document 仍然可见,且事件是仍然可被取消的。

注意: 为了避免不必要的弹出窗口,除非页面已经有过互动,否则可能不会显示beforeunload创建的询问窗口。对于特定的浏览器列表,请参阅浏览器兼容性部分。

语法

window.onbeforeunload = funcRef
  • funcRef 是函数或函数表达式的引用。
  • 这个函数应该设置一个字符串到事件对象的 returnValue 属性上,且返回该字符串。

示例

window.onbeforeunload = function(e) {
  var dialogText = 'Dialog text here';
  e.returnValue = dialogText;
  return dialogText;
};

注意

当事件返回了一个非空值时,将需要用户确认是否 unload 页面。在大部分浏览器中,事件的返回值将在对话框中显示。在 Firefox 4 及以后,返回值将不会显示给用户。作为替代,Firefox将会显示"This page is asking you to confirm that you want to leave - data you have entered may not be saved." 请查看bug 588292.

Since 25 May 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. See the HTML5 specification for more details.

Note also that various mobile browsers ignore the result of the event (that is, they do not ask the user for confirmation). Firefox has a hidden preference in about:config to do the same. In essence this means the user always confirms that the document may be unloaded.

You can and should handle this event through window.addEventListener() and the beforeunload event. More documentation is available there.

Specifications

The event was originally introduced by Microsoft in Internet Explorer 4 and standardized in the HTML5 specification.

Specification Status Comment
WHATWG HTML Living Standard
The definition of 'GlobalEventHandlers' in that specification.
Living Standard  
HTML5.1
The definition of 'GlobalEventHandlers' in that specification.
Working Draft  
HTML5
The definition of 'GlobalEventHandlers' in that specification.
Recommendation  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 1.0 1 4 12 3
Custom text support removed 51.0 44.0 (44.0)   38 9.1
Feature Android Android Webview Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile Chrome for Android
Basic support ? (Yes) ? ? ? (no) defect (Yes)
Custom text support removed ? 51.0 44.0 (44.0)       51.0

See also

文件標籤與貢獻者

 此頁面的貢獻者: hstarorg
 最近更新: hstarorg,