Harsh K
Harsh K

Reputation: 79

How to use chrome.storage along with a remotely hosted database for a chrome extension?

I am working on a chrome extension which has to store data of its user. For that I am using a hosted server which is running a mysql database. But currently any addition or change in data fires a request to the hosted server.

Chrome extension provides chrome.storage.local API which is suitable to store data upto 5mb. I want to take advantage of this storage API to reduce number of requests to my hosted server by using it as a temporary storage.

I am planning to use chrome.storage.onChanged.addListener and chrome.storage.local.getBytesInUse to check if data stored crosses a certain threshold value and then only fire an ajax request to the remote server to save the data. Upon successful response, the old data in chrome.storage will be flushed off.

But there are chances of losing some new data which is created during the process of request/response cycle from the server.

How can I prevent any loss of data? Is there any alternative solution to this optimization problem of reducing number of requests to the remote server from the extension?

Thanks.

Upvotes: 2

Views: 1294

Answers (1)

Eejdoowad
Eejdoowad

Reputation: 1381

This isn't really a question about chrome extensions. It's more about persistent databases that work offline and synchronize intelligently. Which happens to be a very hard problem to do right.

The easiest solution is to use chrome.storage.sync. That buys you persistence for free with the caveat of limited storage. You should definitely see if this is feasible before trying other options.

Otherwise, I recommend looking into 3rd party options before rolling your own solution. You might have heard of progressive web apps, which work offline, and sync when internet is available.

An article about the advantages of progressive web apps

Google Tutorial

PouchDB, a well regarded web database that works offline and syncs to other databases

Look into those. It'll be well worth the trouble. otherwise you'll just end up building hacks on top of hacks trying to get syncing to work.

... one last thing... make sure to add your remote database's URL to your manifest's permissions.

Upvotes: 2

Related Questions