Unsaved changes

I have a page with a javascript block editor where a user can create / edit a post. On that page there is a “save draft” button that should be manually clicked.

I would like to protect the users from accidentally closing the window or navigating away and thus losing the unsaved changes.

I have a Rails 7 application that uses Stimulus / Turbo.

Currently I use this solution:

I am not 100% satisfied because on mobile it may not work in some circumstances (e.g. if the users closes all the browser tabs or apps).

Also you need to manage two separate events: window onbeforeunload and turbo:before-visit… for some strange reasons sometimes I get both the warnings, as if both the events occurred.

Is there any better strategy?

Have you considered temporarily saving the user’s input to Local Storage?

That will also preserve the input in the case of a browser crash.