11

I would like to store a setting of my extension - being changed by the popup:

chrome.storage.local.set({'extension-status': 'on'}, function() {
    console.log('extension on status stored');
}

And receive update in my bakground page when this setting is changed:

chrome.storage.onChanged.addListener(function(changes, namespace) {
     console.log("change recived!");
});

I see the message "extension on status stored" in the logs of the popup but do NOT see "change received" in the logs of the background page.

How can I react on the changes of this stored object?

nagy.zsolt.hun
  • 6,292
  • 12
  • 56
  • 95
  • 4
    Are you actually changing the value, or just setting it to the same ("on")? – Scott Jul 23 '14 at 20:09
  • @ScottF It does not matter if OP is changing the value or not. If listener is there and you set the value, your listener should be invoked everytime. I just tried it and it works. – Sachin Jain Jul 24 '14 at 04:29
  • 1
    @blunderboy That is not true. Open the console and run: `chrome.storage.onChanged.addListener(console.log.bind(console))`, then `chrome.storage.local.set({asdf:"on"})`. You will see the change. Continue running `chrome.storage.local.set({asdf:"on"})`. No more changes are sent. – Scott Jul 24 '14 at 15:51
  • @scott I tried it. If you say i will try it once more time and let you know. – Sachin Jain Jul 24 '14 at 15:52
  • 2
    I'm experiencing this problem, and definitely changing the value. No event firing in the background page. – stickfigure Jun 22 '21 at 22:35

2 Answers2

2

This is an old question but still relevant as of March 4th, 2023.

So for those like me encountering this issue here is my solution.
In short, in chrome use storage.session, not storage.local.

storage.session is available from chrome 102 but not available on firefox.

// manifest.json
{
  ...
  "permissions": [..., "storage", ...],
  "minimum_chrome_version": "102",
  ...
}
// service-worker.ts
function storageOnChanged(changes: {[key: string]: chrome.storage.StorageChange}) {
  console.log(changes); // {key : { newValue: 'value' }}
}
chrome.storage.session.setAccessLevel({ accessLevel: 'TRUSTED_AND_UNTRUSTED_CONTEXTS' });
chrome.storage.session.onChanged.addListener(storageOnChanged);
// content-script.js
chrome.storage.session.set({ key: 'value' }).then(() => {
  console.log('key is set to ' + 'value');
});

As for Firefox, well, I didn't test it.

Micka
  • 1,648
  • 1
  • 19
  • 34
-1

What do you really want to do with this data?

This question seems old, but in Manifest v3 there are service workers, which can be inactive.

Probably alarms can stop them.

https://developer.chrome.com/docs/extensions/mv3/migrating_to_service_workers/

AlexWayfer
  • 39
  • 6