chrome.storage.sync has various quotas, making it non-trivial to use.
There's no built-in efficient way to get the key count. I can:
— get all the data with chrome.storage.sync.get() and count the keys before every operation. This is unnecessarily slow.
— store keyCount property, and keep it updated on every set/remove/clear. This adds more complexity.
Alternatively, I can use try/catch and rely on the error message to remove the oldest items and retry the add operation (similar example below).
So far, I ended up with this:
chrome.storage.sync.set(newItem).then(function(a) {
// Ok
}).catch(function(er) {
if (er.message === "QUOTA_BYTES quota exceeded") {
// Calculate the approx size of the new item, then remove the oldest items until the new item fits, then retry sync.set.
}
});
Is that what extension developers are expected to do? To rely on error messages?