Simulate shutting down scenario in MV3 extensions

22 views
Skip to first unread message

Thien Hoang

unread,
3:26 AM (2 hours ago) 3:26 AM
to Chromium Extensions
In MV3, extension service workers can be shut down when Chrome feels like it, it is advised not to use global variables. The documentation only has one small section about this and I have to make so many assumptions, so I want to test myself, to see what exactly would happen. Is there any reliable way to force shut down an extension the same way Chrome would?

I tried "terminate" in chrome://inspect/#service-workers but when the extension wakes up (due to some events?), the whole service worker script is re-run. Is that what's supposed to happen? I imagine that when the extension wakes up, only the event listeners (corresponding to the events that woke up the extension) will run, and the properties of the class will be undefined.

Below is how my worker script is written:

class X {
  constructor() {
    this.p = { a: 1, b: 2 };
  }
  init() {
    chrome.webNavigation.onCompleted.addListener(this.onPageLoad.bind(this));
  }
  onPageLoad() {
    console.log(this.p.a, this.p.b);
    this.p.a += 1;
    this.p.b += 2;
  }
}

new X().init();

I want to test to know, after my extension is shut down and restarted:
- Will `init` rerun?
- What will happen to `this.p`? Will it be `undefined` when `onPageLoad` is run?

Is it possible to simulate the scenario? If not, what is the known effect in theory?

Any lead is appreciated. Thanks in advance!

woxxom

unread,
4:00 AM (1 hour ago) 4:00 AM
to Chromium Extensions, Thien Hoang
> I tried "terminate" in chrome://inspect/#service-workers but when the extension wakes up (due to some events?), the whole service worker script is re-run. Is that what's supposed to happen?

Yes.

Will `init` rerun?

Yes.

> What will happen to `this.p`? Will it be `undefined` when `onPageLoad` is run?

It'll be the same this.p, because the script simply re-runs, there's no magical "resuming".

The documentation for service workers uses fancy nonsensical words like "tearing down" or "shutting down", but what actually happens is that the worker is simply terminated. Period. Later, the worker is started on an event and there's no magical "spinning up", it just runs the specified service_worker script like any other JavaScript file i.e. fully from start to end, calling addListener to register event listeners, then the browser calls the one that corresponds to the event that woke the service worker.
Reply all
Reply to author
Forward
0 new messages