Hi all,
This is a request for comment.
I'm
working on an extension that loads a sidebar into a user's tabs using a
content script, and I'm trying to understand best practices for how to
make sure the state is consistent across all those tabs' content
scripts.
For
example, we have a series of checkboxes in our sidebar. Each time a
user toggles a checkbox, we save the new setting into
chrome.storage.local, and we want that change to automatically propagate
to the other tabs' content scripts.
We
are currently doing this using the chrome.storage.onChanged event to
detect changes to stored values, and automatically propagate those
changes through to the UI.
However,
I'm concerned about race conditions for complex cases (e.g., if we want
to change an attribute of an object saved to local storage), and am
wondering if there is a framework that provides a more general best
practice.
From what I can tell, it seems like there could be two approaches:
- Create
a dedicated background script that handles all updates to state. When
we want to update state in a content script, the content scripts send a
message to the background script, which handles the state update and
then broadcasts the results back to the content scripts (either via a
message event or a storage onChanged event). Consistency then comes from
the fact that messages are handled in the order they are received, so
we can guarantee some "atomicity" for the steps executed in response to
each message.
- Introduce locks to our use of the chrome.storage APIs.
Is one of these approaches preferred? Are there other approaches?
From initial research, I found the
webext-redux extension implementing
an approach in the spirit of (1) but it's no longer maintained (nor are
it's forks); for (2) I found many proposals / snippets describing
locks, but no maintained or widely-used packages - and I also found
this message that suggested that trying to build a locking system around chrome.storage was a flawed approach.
Thank you for any thoughts in advance,
Tony