Clean IndexedDB when tab is closing
Asked Answered
D

1

8

I need to keep some data in indexedDB instead on sessionStorage as amount of data is more than 5 MB.

I'm confused about cleanup strategy as in case of page reload or navigation to the other page I need this data to be kept, but if user closes browser tab I'd like to remove it to save place.

How can I do that? Need it to be working at least in Chrome.

Drosophila answered 15/4, 2020 at 22:14 Comment(3)
My knowledge here is a bit rusty but you can bind to the unload or beforeunload events fired on the window. The behavior in browsers varies, and unfortunately I think these events get fired always, when tab closed and page refreshed. Perhaps a better strategy, is on load, cleanup the old data. Is it ok to leave it there indefinitely?Outfight
@Josh, how can I understand that some data is not used? There can be multiple tabs and I don't want to remove data of neighbour tab.Drosophila
I do not believe you have any indicator within indexedDB regarding which tab was responsible for storing the data. Perhaps you can invent a way to do this yourself such as by storing an extra property that uniquely identifies each tab.Outfight
F
5

You can store an indicator in the session storage, then delete the database if that value does not exist.

(async() =>
{
  if (!sessionStorage.getItem('just-a-placeholder'))
  {
    indexedDB.deleteDatabase('temp');
    sessionStorage.setItem('just-a-placeholder', true);
  }

  const databases = await indexedDB.databases();
  console.log(databases.find(db => db.name === 'temp') !== undefined)
  await indexedDB.open('temp');
})();

Sadly StackOverflow does not run snippets in a way I could show this here but here is a JSFiddle to show it in action.

Foreigner answered 15/4, 2020 at 22:40 Comment(3)
My question is: When I should delete data from indexedDB? Can't understand how you answer relates to it.Drosophila
The database will be removed when the sessionStorage is cleared aka when the user closes the browser, since your question was fundamentally asking for more storage on the sessionStorage object.Foreigner
No as indexedDB is a persistent storage.Drosophila

© 2022 - 2024 — McMap. All rights reserved.