Trace
Trace

Reputation: 18869

Chrome extension: sync localstorage with server api

I'm dealing with the conceptual problem that my Chrome browser extension needs to sync with a server in order to persist data in a database.
For my extension I want to save cleaned tab data to the server.

The problem with extensions is that there is no immediate visual clue as for when a network request succeeded or failed.
Therefore there needs to be a sort of syncing mechanism that backups data locally, in order to be synced in the background. If a backup failed, there should be an automatic sync starting when the service comes back online.

I have no prior experience with this scenario, but what I have in mind is:

Is there an alternative way to periodically check the localstorage in order to sync data to the server in case the remote server is unavailable for a period?

If there is a better (common) way for achieving desired result, I would like to hear it.

Upvotes: 0

Views: 895

Answers (2)

amir
amir

Reputation: 116

Depending on the structure of the data being stored, you could probably get by with localStorage. Every time you make a change to a key locally (or add a new one), mark that key as "dirty" (i.e., unsynced). The next time you sync, you'll know which keys/values to sync.

For example, if your data is:

localStorage['tab1'] = '{...}'
localStorage['tab2'] = '{...}'
delete localStorage['tab3']

Store an additional meta key for your syncing mechanism:

localStorage['$syncinfo$'] = JSON.stringify({
  dirty: ['tab1', 'tab2', 'tab3']
})

Then when you go to sync (roughly):

for(const key of JSON.parse(localStorage['$syncinfo$']).dirty) {
  if(localStorage[key] !== undefined) {
    // sync updated (or new) value to server
    // remove key from dirty array
  } else {
    // remove deleted value from server
    // remove key from dirty array
  }
}

Of course, you'll want to handle errors and only update the dirty array when the server sync is successful, but this is a simple way to accomplish what you want, I hope :)

If you're looking for a solution that does this, you could try localForage, which is a localStorage-compatible API, coupled with a localForage driver that syncs data into a remote data store like KVdb.io, or another one with a compatible driver. (Disclaimer KVdb.io is built by me.)

Upvotes: 3

Trace
Trace

Reputation: 18869

After some research I figured that setTimeInterval / setTimeout will do the job.

  • Save cleaned tabs to chrome storage
  • Make network request
  • Clean up on success
  • Mark as failed on error
  • Check periodically for failed states
  • Mark for cleanup on success
  • Cleanup

The api should be adapted accordingly so it can handle multiple bundled requests to keep the amount of network requests low.

Upvotes: 1

Related Questions