BeforeUnloadEvent

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

BeforeUnloadEventbeforeunload イベントのインターフェイスです。

beforeunload イベントは、ウィンドウ、文書、そのリソースがアンロードされようとしているときに発生します。

Event の returnValue プロパティに空文字列でない値が代入されると、ダイアログボックスが現れ、ユーザーにページを離れるかどうかの確認を求めます(下記の例を参照)。値が指定されなかった場合、イベントはサイレントで処理されます。実装によっては、フレームまたは埋め込まれたフレームがユーザージェスチャまたはユーザーの操作を受け取った場合にのみ、ダイアログボックスを示すものもあります。詳しくはブラウザーの互換性を参照してください。

メモ: セキュリティ上の理由から、返す文字列の代わりに、ウェブページの制御しない一般的な文字列のみが示されます。

Event BeforeUnloadEvent
バブリング なし
キャンセル
対象オブジェクト defaultView
インターフェイス Event

js
window.addEventListener("beforeunload", (event) => {
  event.returnValue = "\\o/";
});

// is equivalent to
window.addEventListener("beforeunload", (event) => {
  event.preventDefault();
});

WebKit 派生ブラウザーは、ダイアログボックスについては仕様に従っていません。ほぼクロスブラウザーで動作する例としては、下記の例のようなものがあります。

js
window.addEventListener("beforeunload", (e) => {
  const confirmationMessage = "\\o/";

  // Gecko + IE
  (e || window.event).returnValue = confirmationMessage;

  // Safari, Chrome, and other WebKit-derived browsers
  return confirmationMessage;
});

仕様書

Specification
HTML
# the-beforeunloadevent-interface

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
BeforeUnloadEvent
returnValue
Deprecated
User interaction required for dialog box

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
No support
No support
Deprecated. Not for use in new websites.
Has more compatibility info.

関連情報