unload. Modern browsers do not reliably allow that. This version preserves the page-exit demonstration by recording lifecycle events and showing them when the page is displayed again.No previous page-exit event recorded in this tab yet.
Leave this demo and open the tutorial Reload demo
After leaving, use your browser Back button to return. The message above will show the lifecycle event recorded before the page was hidden.
Return to Tutorial on unload and modern alternatives.
const statusBox = document.getElementById('status');
const storageKey = 'plus2net-page-exit-demo';
function showStoredEvent() {
const message = sessionStorage.getItem(storageKey);
if (message) statusBox.textContent = message;
}
window.addEventListener('pageshow', showStoredEvent);
window.addEventListener('pagehide', (event) => {
const message = `pagehide fired before leaving. bfcache persisted: ${event.persisted}`;
sessionStorage.setItem(storageKey, message);
});
window.addEventListener('unload', () => {
sessionStorage.setItem(storageKey, 'unload fired. This event is legacy and may be skipped by the browser.');
});
showStoredEvent();
<p id="status" aria-live="polite">No previous page-exit event recorded yet.</p>
<a href="onunload.php">Leave this demo and open the tutorial</a>
This is the original facility for reference. The alert itself is no longer dependable during page unload.
<body onunload="alert('thanks for visiting plus2net')">
You should get one alert message when you close or exit this page.
</body>