Is there a way to watch storage changes for all keys, or keys matching a prefix?

I want to get updates on all changes to storage, or all changes to keys matching "example_*"
2 Replies
Sam
Sam•2mo ago
Yep. This is a snippet I use to observe and log all changes to local storage. You can just update the areaName filter to your needs.
chrome.storage.onChanged.addListener((changes, areaName) => {
if (areaName === 'local') {
for (const [key, { oldValue, newValue }] of Object.entries(changes)) {
console.log(
`Storage key "${key}" in namespace "${areaName}" changed.`,
`Old value was "${oldValue}", new value is "${newValue}".`,
);
}
}
});
chrome.storage.onChanged.addListener((changes, areaName) => {
if (areaName === 'local') {
for (const [key, { oldValue, newValue }] of Object.entries(changes)) {
console.log(
`Storage key "${key}" in namespace "${areaName}" changed.`,
`Old value was "${oldValue}", new value is "${newValue}".`,
);
}
}
});
I put that in a message handler or port then look at the dev tools for the service worker. If you want to get access to that in a CSUI component I believe it would be a similar callback. In my CSUI component I have a singleton setup like this.
import { Storage } from '@plasmohq/storage';

const chromeLocalStorage = new Storage({
area: 'local',
});

export { chromeLocalStorage };
import { Storage } from '@plasmohq/storage';

const chromeLocalStorage = new Storage({
area: 'local',
});

export { chromeLocalStorage };
which I then import across different components. Honestly not sure if its needed, it's just kind of part of the code now. Either way in my CSUI component I then create a useEffect hook like this
useEffect(() => {
const storageWatchCallbacks: StorageCallbackMap = {
['storageKeyYouWantToObserver']: (storageChange) => {
console.log(storageChange.newValue);
},
};
chromeLocalStorage.watch(storageWatchCallbacks);
return () => {
chromeLocalStorage.unwatch(storageWatchCallbacks);
};
}, []);
useEffect(() => {
const storageWatchCallbacks: StorageCallbackMap = {
['storageKeyYouWantToObserver']: (storageChange) => {
console.log(storageChange.newValue);
},
};
chromeLocalStorage.watch(storageWatchCallbacks);
return () => {
chromeLocalStorage.unwatch(storageWatchCallbacks);
};
}, []);
Not sure if there is a generic watch all that you can use there. Might have access to the chrome.storage API there too. The 2nd method won't work for your wild card scenario unfortunetly.
ortutay
ortutayOP•2mo ago
ok--I was hoping to avoid reference chrome.storage but looks like Plasmo storage only lets you watch specific keys, not the whole thing
Want results from more Discord servers?
Add your server