admin管理员组

文章数量:1415644

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.

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.

Share Improve this question asked Apr 15, 2020 at 22:14 QwertiyQwertiy 21.6k17 gold badges67 silver badges142 bronze badges 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? – Josh Commented Apr 16, 2020 at 2:40
  • @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. – Qwertiy Commented Apr 16, 2020 at 7:57
  • 1 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. – Josh Commented Apr 16, 2020 at 17:39
Add a ment  | 

1 Answer 1

Reset to default 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.

本文标签: javascriptClean IndexedDB when tab is closingStack Overflow