The beforeunload event was intended to give a user a chance to save unsaved work before leaving a page. Safari appears unable to enable this feature.
To be clear: This original use case for beforeunload is exactly what I need. I am not trying to use beforeunload to trigger beaconing, empty localStorage, etc. I am not using Promise or await.
Using this test script on a blank HTML page in my Safari 15-16 browser, I am able to see the beforeunload alert, but the page navigates immediately to the next location:
<script>
function beforeUnloadListener(event) {
if (true) {
event.preventDefault();
// eslint-disable-next-line no-param-reassign
event.returnValue = 'This message is ignored in modern browsers.';
return event;
}
return null;
}
addEventListener('beforeunload', beforeUnloadListener, { capture: true });
</script>
(I first must click into the window to make sure the browser detects interaction.)
- if I close the browser window, the alert blocks the window from being closed
- If I navigate to another CACHED page in safari, the alert is shown
I then WAIT a few seconds to observe the alert. What happens next in Safari is weird.
The alert does not block navigation. I am taken to the new page with the alert still being displayed. The alert is then "useless" in the sense that pressing the affirmative or negative buttons dismisses the alert, but has no other effect.
This is not the expected behavior in Chrome or Firefox. In these, the page will not navigate or cancel navigation until an alert option is clicked.
Is this by design? I doubt it, because leaving the alert up but navigating to another page is not an acceptable behavior.
Are there work-arounds? I can't find a way to support this feature in Safari.