Home

beforeunload

beforeunload is a browser event that fires on a window or frame when the document is about to be unloaded, such as during navigation to a different page, a reload, or when the user closes the tab or window. It is intended to give the page a last chance to warn the user about potential data loss.

The event is cancelable. If a listener calls preventDefault or sets a returnValue, many browsers may show

Usage patterns typically involve checking whether the page has unsaved changes and, if so, triggering a prompt.

Limitations and considerations include user experience and interoperability concerns. Because prompts can be disruptive, beforeunload should

Alternatives and best practices focus on proactive data preservation. Where possible, autosave changes or use the

a
confirmation
dialog
asking
the
user
to
confirm
leaving
the
page.
The
exact
dialog
text
is
controlled
by
the
browser
and
cannot
be
customized
by
the
page
in
modern
environments.
Example
usage
often
takes
the
form
of
registering
a
beforeunload
listener
that
looks
at
a
flag
indicating
unsaved
work
and
then
sets
a
nonempty
returnValue
to
request
confirmation.
be
used
sparingly
and
only
when
there
is
meaningful
potential
data
loss.
Not
all
navigations
will
trigger
a
prompt,
and
some
mobile
browsers
may
not
display
one.
The
content
of
any
prompt
is
standardized,
and
some
browsers
impose
extra
restrictions
on
when
a
prompt
appears.
Page
Lifecycle
API
(with
visibilitychange
or
pagehide)
to
perform
saves.
If
a
prompt
is
used,
keep
it
limited
to
essential
situations
and
avoid
relying
on
it
for
critical
functionality;
consider
using
reliable
background
saving
mechanisms
like
navigator.sendBeacon
for
non-blocking
transmission
at
unload.