Detecting unsaved work and autosaving
When using the BEE editor on beefree.io you might have noticed that if you start creating a message, leave the site, and go back to it at a later time, you are asked whether to continue working on the message that you were working on earlier, or start with a new one.
The autosave parameter and onAutoSave function
Since this is something that you may be interested in adding to your own application, here is how we did it on beefree.io, in a few words.
- While the user works on the message inside the editor there is an auto-save event that is triggered every 15 seconds.
- That's an option that you can configure when you initialize the plugin, by using the autosave parameter. The parameter's value is the number of seconds between auto-saves. If you pass the parameter with a value of "false", no auto-saving is done.
- When the auto-save event is fired, it calls the onAutoSave function and passes the JSON of the message to it.
- On beefree.io, the onAutoSave function saves the JSON in the browser's local storage. When the user comes back (using the same browser) the beefree.io Web site checks the local storage and adds a new element to the UI, asking the returning visitor whether they wish to continue editing the previous message.
Why only the message JSON
There is a reason why only the JSON of the message is passed to the onAutoSave function and not also the HTML (unlike when the onSave or onSaveAsTemplate functions are invoked). The reason is that parsing the JSON and generating the HTML of the message takes a few moments, during which the user cannot interact with the editor and a "waiting" icon is shown. If this were to happen every time a message is auto-saved, it would not lead to a good user experience.
Removing saved message drafts
You could decide to delete the message draft when the user saves the message (i.e. when the onSave function is triggered). This way returning visitors to your application will be prompted to start working on the previous document only if something went wrong before saving that message.
If instead they had saved the message, the draft would no longer be there and therefore would not be prompted to do so.
Where to save message drafts when auto saving
In the example mentioned above about beefree.io we mentioned using the browser's local storage. That's because there is no user sign-up to access the editor on the site: there is no account to save the data to.
In the case of your application, you will likely have some sort of user identification and therefore could save the data to a database, preventing the issue of the data being lost if the user were to used a different browser.