0

I have a code like below in my MV3 extension:

import _ from 'lodash'; 

const storageKey = 'state';
let state;
(async () => {
  state = await chrome.storage.local.get(storageKey);
  listener();
})();

const update = async (data) => {
  await chrome.storage.local.set({[storageKey]: data});
}

let lastPick;
const listener = async () => {
  const pick = _.pick(state, ...);
  if (_.isEqual(pick, lastPick))
    return;
  lastPick = pick;
  ...
  // do some stuff
}

chrome.storage.onChanged.addListener((changes, area) => {
  if (area !== 'local' || !(storageKey in changes))
    return;
  const {newValue} = changes[storageKey];
  state = newValue;
  listener();
});

chrome.tabs.onActivated.addListener(async (data) => {
  ...
  update(...);
  ...
  update(...);
  ...
  update(...);
});

With classic Manifest V2 extension I could be sure that value of lastPick will be always persisted through listener calls (which in turn caused by multiple update calls), so "some stuff" logic within listener won't be broken.

But what about Manifest V3, or to be more precise, its service workers? Can I be confident the above logic won't be broken there?

hindmost
  • 6,828
  • 3
  • 23
  • 36
  • If the service worker dies, the code that didn't complete won't run at all. The thing you imply isn't even possible: a worker can't die, resurrect, and keep running code from the previous run. See also [Persistent Service Worker in Chrome Extension](https://stackoverflow.com/a/66618269) – wOxxOm May 26 '21 at 15:32
  • @wOxxOm It seems you got me wrong. I'm not asking about persistent service worker, nor want a worker to resurrect from the previous run. All async code in my example runs within the same chrome API event listener: I change `chrome.storage` data a few times from `chrome.tabs.onActivated` listener. And I also have another listener - for `chrome.storage.onChanged` event. My question is whether the latter will be called in the same context as the former if all the calls of the latter (`chrome.storage.onChanged`) are caused by the same call of the former one? – hindmost May 26 '21 at 17:15
  • 1
    The context is an overloaded term. It can mean the worker itself as a concept opposed to a tab so it will always be the same. Whether it'll be the same **life cycle**, depends on how much time has passed. If it's more than 30 seconds since the last API event and there are no external connections (e.g. via chrome.runtime ports) then the worker dies. Any subsequent event will start the worker anew just like a page in a new tab starts with a fresh JS environment. If you want to ensure the events are called within the same life cycle you'll have to keep the worker alive. – wOxxOm May 26 '21 at 17:35

0 Answers0