The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point.

If a string is assigned to the returnValue Event property, a dialog box appears, asking the user for confirmation to leave the page (see example below). Some browsers display the returned string in the dialog box, others display a fixed message. If no value is provided, the event is processed silently.

Note: To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with, or even not at all.

Bubbles No
Cancelable Yes
Target objects defaultView
Interface Event


Property Type Description
target Read only EventTarget The event target (the topmost target in the DOM tree).
type Read only DOMString The type of event.
bubbles Read only Boolean Does the event normally bubble?
cancelable Read only Boolean Is it possible to cancel the event?
returnValue DOMString The current return value of the event (the message to show the user).


window.addEventListener("beforeunload", function (event) {
  event.returnValue = "\o/";
// is equivalent to
window.addEventListener("beforeunload", function (event) {

WebKit-based browsers don't follow the spec for the dialog box. An almost cross-browser working example would be close to the following:

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";
  e.returnValue = confirmationMessage;     // Gecko, Trident, Chrome 34+
  return confirmationMessage;              // Gecko, WebKit, Chrome <34


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.

Various browsers ignore the result of the event and do not ask the user for confirmation at all. The document will always be unloaded automatically. Firefox has a switch named dom.disable_beforeunload in about:config to enable this behaviour.

Using this event handler in your page prevents Firefox from caching the page in the in-memory bfcache. See Using Firefox 1.5 caching for details.


Specification Status Comment
WHATWG HTML Living Standard
The definition of 'beforeunload' in that specification.
Living Standard  
The definition of 'beforeunload' in that specification.
Recommendation Initial definition

Browser compatibility

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

See also

Document Tags and Contributors

 Last updated by: SphinxKnight,