Search code examples
javascripthtmlfrontendweb-worker

Cannot access some functions and variables from inside a WebWorker


I have an issue with calling a function from main inside the web worker that I've created. I created an object similar to enum in Java language :

const states = {
    START: 'start',
    ADDCHAR: 'addchar',
    WORDBEFORE: 'wordbefore',
    REMOVECHAR: 'removechar',
    RESET: 'reset'
  }

And each element have a state that I use in the following code:

  self.addEventListener('message', function(e) {
  while( true ){
      switch ( state ){
          case states.START: 
                              start();
                              state = states.ADDCHAR;

          case states.ADDCHAR:
                              addchar();
                              state = states.WORDBEFORE;

          case states.WORDBEFORE:
                              sleep(3000);
                state = states.REMOVECHAR;

          case states.REMOVECHAR:
                              removeChar();
                              state = states.RESET; 
          case states.RESET:
                              reset();
                state = states.START;
      }
      sleep(1000);
  }
});

The problem is that I can't access functions from main: start(), addchar() etc.

How can I reach those functions from inside the web worker? I send messages from main to the web worker, but it doesn't work to do the 'connection' from web worker to the main (and still sending messages doesn't resolve all my problems because I have to call specific functions from the main inside the switch statement).

I tried numerous modification to the code but I couldn't make it work out.


Solution

  • Functions and global variables in the scope of JavaScript scripts loaded in the browser window are not accessible to the web worker.

    You can use importScripts to import them to your worker.

    Quoting from the documentation at MDN:

    Worker threads have access to a global function, importScripts(), which lets them import scripts. It accepts zero or more URIs as parameters to resources to import; all of the following examples are valid:

    importScripts();                         /* imports nothing */
    importScripts('foo.js');                 /* imports just "foo.js" */
    importScripts('foo.js', 'bar.js');       /* imports two scripts */
    importScripts('//example.com/hello.js'); /* You can import scripts from other origins */