Safari 15 prompts the beforeunload alert, but does not block navigation

Using the example provided by MDN, the beforeunload event is working in my Safari browser:

const beforeUnloadListener = (event) => {
  event.preventDefault();
  return event.returnValue = "Are you sure you want to exit?";
};

addEventListener('beforeunload', beforeUnloadListener, { capture: true });

(I first must click into the window to make sure the browser detects interaction.)

  1. if I close the browser window, the alert blocks the window from being closed
  2. If I navigate to another page, the alert is shown
  3. However, when I navigate to another page, 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 there any work-around? It seems it would be better to not show the alert at all than to show the alert while asynchronously unloading the current page and loading another page.

I need to use this event to inform a user they may want to save changes to a document before leaving the page. This was the original use case for beforeunload.

!!! It's very important in this test to wait and watch the alert. The behavior I describe is navigation, so we must wait for the link to resolve and page GET to commence before you see this issue.

This is the kind of defect you might not catch in automation testing, because unless there is a pause after the alert is shown, the test might pass.

!!!! This only happens when clicking on a bookmarked link. If you type some link into the navigation bar, it behaves as expected.

Specifically this applies to CACHED pages only.

Safari 15 prompts the beforeunload alert, but does not block navigation
 
 
Q