The unload event is a historical page-exit event. Older examples used it to run JavaScript when a user left a page or closed a tab. Modern browsers intentionally restrict and sometimes skip this event, so it should not be used for critical work.
unload for new code. Use visibilitychange for state saving, pagehide when you specifically need a page-hiding/navigation signal, and beforeunload only when a user has unsaved changes and genuinely needs a leave-page warning.Open the page-exit demo in a new tab
The original plus2net demonstration attached an inline onunload handler that attempted to show an alert. That source is preserved here for historical understanding, but the alert is not a dependable modern behavior because user-interface interactions are restricted during unloading.
<body onunload="alert('thanks for visiting plus2net')">
You should get one alert message when you close or leave this page.
</body>
A JavaScript property/listener version of the same legacy event is:
window.addEventListener('unload', () => {
// Do not rely on UI or long-running work here.
});
Browsers may skip unload, particularly in mobile and back/forward-cache scenarios. Dialogs, new windows and other UI operations are ineffective while unloading. This means an exit alert is not a reliable feature to build around.
If the purpose is to observe that a page is being hidden because another history entry is about to be shown, pagehide is a better fit and is compatible with the browser back/forward cache.
window.addEventListener('pagehide', (event) => {
console.log(`Page hidden. Persisted in bfcache: ${event.persisted}`);
});
For automatically saving application state when the user switches tabs/apps or the page becomes hidden, listen for visibilitychange.
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
saveDraft();
}
});
beforeunload can request a browser-generated leave-page confirmation. Modern browsers control the wording and generally require prior user interaction. Register it only while unsaved data exists, because persistent listeners can hurt navigation performance.
function warnAboutUnsavedChanges(event) {
event.preventDefault();
event.returnValue = true; // Legacy support
}
window.addEventListener('beforeunload', warnAboutUnsavedChanges);
Event Handling onMouseOver and onMouseOut
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.