I was experiencing something similar and found that the page needs some kind of interaction before the preventDefault() will work. Make sure you click somewhere on the page or within the app before leaving/refreshing the page.
Here is the documentation... https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
To trigger the dialog being shown when the user closes or navigates the tab, a beforeunload event handler function should call preventDefault() on the event object. You should note that modern implementations:
- Require sticky activation for the dialog to be displayed. In other words, the browser will only show the dialog box if the frame or any embedded frame receives a user gesture or user interaction. If the user has never interacted with the page, then there is no user data to save, so no legitimate use case for the dialog.
- Only show a generic browser-specified string in the displayed dialog. This cannot be controlled by the webpage code.
Also note: using an alert is not recommended within the beforeunload event.