Search code examples
javascriptpromiseindexeddbonbeforeunload

Save to IndexedDB beforeunload


I want to save to IndexedDB before the user leaves my page. I'm doing this periodically, but since it's pretty big, I don't want to save too often.

my current (broken) code is as follows:

window.addEventListener('beforeunload', (event) => {
    persist(state);
});

Here, persist immediately returns a promise and the browser exists before I get the chance to save state.

Unfortunately, doesn't seem like IndexedDB has a synchronous API at this point.

Is there anything I can do to make the browser wait so i can store a value into IndexedDB?


Solution

  • How about you instead save to localStorage on page unload. Then at a later time, check for this value in localStorage and move it into indexedDB when you have more time.