Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get notified when indexedDB entry gets changed in other tab

Tags:

If a user opens multiple instances of a web app in multiple tabs, any instance can be notified of changes to localStorage that any other instance makes by registering a storage event listener. A tab receiving such a notification might then react and e.g. update the UI according to the changes.

Indexed DB doesn't seem to offer a similarly convenient mechanism for such notifications. Would one have to use localStorage to "send" a notification to other tabs whenever making changes to Indexed DB? The only other alternative might be polling, which is clearly inferior to storage events.

like image 600
Thomas W Avatar asked Oct 20 '15 13:10

Thomas W


People also ask

Is IndexedDB shared between tabs?

Data stored in indexedDB is available to all tabs from within the same origin.

Why is it better to use IndexedDB instead of localStorage?

Using localStorage requires creating many individual (in my case, dozens) key/value pairs. Instead, IndexedDB would allow storing an array or object of all form data together. This would make storage much easier and could potentially make retrieving the data much easier.

Is IndexedDB faster than localStorage?

LocalStorage is slightly faster than IndexedDB in all browsers (disregarding the crashes). IndexedDB is not significantly slower when run in a web worker, and never blocks the DOM that way.

Is IndexedDB slower than localStorage?

For instance, IndexedDB doesn't block the DOM when used with a worker, unlike localStorage. However, localStorage is slightly faster than IndexedDB.


2 Answers

There's no current "observer" API defined for Indexed DB. However, it's on the feature request list and there are similar proposals from both Mozilla and Google.

https://github.com/w3c/IndexedDB/issues/51

Which is to say: yes, you need to come up with some custom cross-tab communication mechanism, such as polling, storage events, setting up MessageChannel links (Chrome), BroadcastChannel (Firefox), or using a Service Worker as a relay between clients.


NEWS FLASH!

Chrome has an experimental Indexed DB Observers API. You need to run chrome with --enable-experimental-web-platform-features to use it so it's not useful in production yet. We'd love to get feedback on it - file bugs on the github repo.

like image 87
Joshua Bell Avatar answered Oct 13 '22 00:10

Joshua Bell


Update

  1. Dexie has an add-on for Observables now, in case you start with a new project: https://dexie.org/docs/Observable/Dexie.Observable
  2. Oleg did a solid hook on the Ionic storage wrapper. But that can be created for any local storage library. Solid engineering. https://medium.com/@OlegVaraksin/how-to-make-ionic-storage-reactive-acdd8996f1e6
like image 31
feder Avatar answered Oct 13 '22 01:10

feder