Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
JS: constants for magic numbers in service worker context

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!