I'm trying to understand what I can and can't do with onbeforeunload. I've read the docs in MDN and feel I have... some understanding.
The problem I'm trying to solve:
I have this form with lots of records on it. I'm auto-saving as records are edited. However, if there's an error that prevents saving, users don't always notice while they're making lots of updates.
So, naturally, I want to tell them.
My real problem is that I want to present a list of unsaved changes - lots of records, users shouldn't have to scroll through trying to spot the highlighted ones with errors. Or even search for a string, really.
I've managed to do this but am a little confused. Thus, my question.
I know that I don't control the contents of the message in the confirm alert that is triggered from the onbeforeunload handler.
But do I have any control over what happens in the case of either response (leave or stay)?
My div with unsaved changes shows, regardless of what they choose. It won't prevent leaving, of course, if they choose to leave... but they're confused about why it's showing at all.
With your usual confirm prompt, you control what happens in either case, but this isn't a normal prompt.
Am I understanding correctly? If I am, I'll just endeavor to train them about what's happening. They'd rather see it when they've already said peace and are just waiting for it to happen than not get the prompt at all.
Thanks all!
But do I have any control over what happens in the case of either response (leave or stay)?
If they leave, the unload
event will be triggered next, and you might be able to do something useful there.
If they stay, it's as if they never tried to leave in the first place and you just continue normally.
What you could do is provide some indication of unsaved changes, which the user can see when they're responding to the prompt. There could be a message that changes from "There are unsaved changes" to "Changes are saved" whenever an auto-save is successful, and the input fields with unsaved data might be highlighted in a different color. (SE displays "Draft saved" periodically while I'm editing this answer -- I think it's saving in SessionStorage.)