I have an extension that reads a feed of timestamped messages and alerts users to them.
I track the highest timestamp since user opened a message, anything below that being "read". It works well, but problems start when a user has several Chrome installs: he's presented with items he already read on another machine.
Enter chrome.storage.sync
API. I can set the highest timestamp to sync between instances, but that presents me with a race condition.
If I use chrome.storage.sync.get
immediately after the browser is launched or wakes from sleep, it will get stale local data and will not wait for a sync to happen - tested to be true. So the user is still alerted, even if for a brief period before the alert is cleared - which is confusing.
I can detect extension launch, I can (sort of) detect wake from sleep. Maybe even offline/online events. But what do I do next to give Chrome a chance to sync data? A naive solution would be this:
var syncSleepTimeout = null;
function getUpAndRunning(){
clearTimeout(syncSleepTimeout);
syncSleepTimeout = null;
doActualWork();
}
// Called upon wakeup/start/online event
function justWokeUp(){
// Give sync a chance to happen
syncSleepTimeout = setTimeout(getUpAndRunning, 3000);
}
chrome.storage.onChanged.addListener(function(changes, area){
if(area === "sync" && syncSleepTimeout) getUpAndRunning();
});
To the best of my knowledge, chrome.storage.sync
does not provide any state information or events, not even whether cloud sync is actually enabled by the user. I filed a couple of feature requests to that effect, but they are completely ignored.
- Is there a more elegant solution to this?
- What would be a robust solution of detecting wakeup / getting online events?