How to implement autosave triggers when closing or backgrounding a browser tab?
Listen for the visibilitychange event (state 'hidden') and the pagehide event, then run your save function immediately and synchronously. Do not rely on beforeunload for mobile browsers. Save to storage that survives tab closure, not sessionStorage, and keep the write small and fast.