I have a service worker extension which is using a lot of hard-coded values and definitions. For example, we have a proprietary protocol which defines certain message types which are identified by integers:
const MsgType = {
MSG_TYPE_1: 0, // not really called like this, just an example
MSG_TYPE_2: 1
};
According to my understanding, one cannot rely on global variables in service workers. As such using constants for hard-coded values won't do it. JS does not have any other way to set such hard-coded values.
I can only think of three ways to deal with this:
1- Just use hard-coded values all over your code. I refuse to do this....
2- use functions to return the value such as
function MsgType() {
return {
MSG_TYPE_1: 0,
MSG_TYPE_2: 1
}
}
3- replace const with let and have a function reinitialize everything:
let MsgType = null;
function setEveryConstantEverywhere() {
if (MsgType != null) {
return;
}
// set everything
}
// in code where SW is expected to wake up then call setEveryConstantEverywhere right at the start.
Is there another way? Am I getting this all wrong?
OK, so I ran some empirical tests and now I have a better understanding.
1- Whenever the extension service worker is loaded again, the complete global context is evaluated BEFORE the event handlers are invoked. This implies that global constants are being RE-defined
2- One can enclose a reference to an object and it will be available in the event handler. However, if the SW has restarted the reference will be to the newly created instance and not the one set before restarting:
const obj = {/*...*/};
chrome.webRequest.onBeforeRequest.addListener((context => _ => {
context === obj; // true
})(obj) ,/*...*/);
Intuitively, one would think the event handler instance being called was the one set before stopping the SW, however this is not so. It seems indeed everything gets completely wiped, then the SW is initialized (run all code in global scope), and only then the event is dispatched.