Search code examples
javascriptconstructorweb-worker

Initializing web workers


It seems the only communication from host to worker is postMessage and onmessage. If the worker requires some dynamic initialization (as in constructor, here: regular expression to use later), what is the best way to do this?

A possibility would be to let data be an object, and have e.g. an action parameter, and to check this on every run. This seems a bit kludgey.


Solution

  • A more ad-hoc approach than Jonas' solution abuses the Worker's name option: You can e.g. pass the regex string in this name and use it later:

    test.js

    var a = new Worker("worker.js", {name: "hello|world"})
    
    a.onmessage = (x) => {
      console.log("worker sent: ")
      console.log(x)
    }
     
    a.postMessage("hello")
    

    worker.js

    var regex = RegExp(this.name);
    
    onmessage = (a) => {
      if (regex.test(a.data)) {
        postMessage("matches");
      } else {
        postMessage("no match for " + regex);
      }
    }