The approach mentioned by Paul is, broadly speaking, the one I'm trying to use as well.
However, I am still not convinced of the absolute reliability of this approach.
I'm working on a special case; I'm migrating an extension that modifies the new browser tab.
I therefore have to manage not only the storage movements made by the SW, but also the movements made by one (or more) extension pages (in my case one or more "new tabs")
and make sure that SW and each page can always read the "most updated" values of these variables\states".
To do this, I exchange a message (in one direction or the other) warning that something may have changed and therefore it is necessary to read all the storage again.
In practice, the first thing the runtime.onMessage handler does is to read (again) the storage.
The SW may fall asleep and wake up when events are triggered.
In this case, upon reactivation, the SW would proceed to read the entire storage again, but could also react to the same events when awake; therefore I cannot rely on the latest storage dump, but will have to read everything again when each event is triggered (exactly as Paul indicated).
Realizing that every event is asynchronous, I wonder how I can be sure that the storage read operation can always be considered reliable.
I mean, let's say the SW responds to an alarm and that a storage variable is set in the chrome.alarms.onAlarm handler.
Now, if at this precise moment another event occurs, for example a message from an extension page,
what ensures that the function that handles the alarms.onAlarm event ends before the message handling function starts (and therefore before reading the aforementioned variable)?
Referring to @Paul's last post we are sure that the statement:
> "Whenever any state change occurs, write it to storage.session immediately" <is it enough to sleep peacefully?
Here is some sample code:
//Service Worker
readAllStorage() //reading all storage...
.then(cachedStorage => {
chrome.storage.session.get({'bar': 0}, itm => {
console.log('bar = ', itm.bar) //at the begining console shows: bar = 0
})
});
chrome.alarms.onAlarm.addListener(function(alamrm) {
readAllStorage() //reading all storage...
.then(cachedStorage => {
console.log(cacheStorage);
//NOW I'M GOING TO SET "BAR" BUT IN THE MEANTIME AN INCOMING MESSAGE ARRIVES BEFORE THE WRITE OPERATION HAS ACTUALLY BEEN COMPLETED!!!
chrome.storage.session.set({'bar': 1}, _ => {
//EXECUTION WENT TO "CHROME.RUNTIME.ONMESSAGE" BUT SOON IT WILL RETURN HERE TO FINISH PENDING WORK.
chrome.action.setBadgeText({'text': 'hi'})
});
})
})
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
readAllStorage() //reading all storage...
.then(cachedStorage => {
chrome.storage.session.get({'bar': 0}, itm => {
console.log(itm.bar) //WHAT IS THE VALUE OF "BAR"? 0 OR 1 ?
})
})
});