title: How to pass functions to JavaScript Web Worker
body: <p>I would like to pass a function (or functions) via a <code>postMessage()</code> to a web worker, because I can't refer to regular files.</p>
  
  <p>To kick the web worker off, I am passing an object URL (created from a Blob) to the <code>Worker</code> constructor. Then I am passing a message, but so far no luck putting a function in the message. </p>
  
  <p>The (JSON) message cannot contain functions directly (as stipulated <a href="https://developer.mozilla.org/en-US/docs/DOM/Using_web_workers?redirectlocale=en-US&amp;redirectslug=Using_web_workers#Passing_JSON_data" rel="noreferrer">here</a>), and although importScripts is theoretically allowed, I have not had any success using it so far in Chrome or Firefox.</p>
  
  <p>The body of the html file:</p>
  
  <pre><code>&lt;div id="divText"&gt;1234&lt;/div&gt;
  &lt;script&gt;
      var greeter = function greet(name) {
          return "hello " + name;
      };
      function webWorkerWorker() {
          self.postMessage("started1");
          self.onmessage = function(event) {
              importScripts(event.data.content);
              self.postMessage("importScripts success");
              var result = greeter("john");
              self.postMessage(result);
          };
      }
      var functionBody = mylib.extractFunctionBody(webWorkerWorker);
      var functionBlob = mylib.createBlob([functionBody]);
      var functionUrl = mylib.createObjectURL(functionBlob);
  
      var functionBody2 = mylib.extractFunctionBody(greeter);
      var functionBlob2 = mylib.createBlob([greeter]);
      var functionUrl2 = mylib.createObjectURL(functionBlob2);
  
      var worker = new Worker(functionUrl);
      worker.onmessage = function(event) {
          document.getElementById("divText").innerHTML = event.data;
      }
      worker.postMessage({
                  type: "init",
                  content: functionUrl2
              });
  &lt;/script&gt;
  </code></pre>
  
  <p>Currently it results in setting the divText value to "importScripts success".</p>
  
  <p>Am I doing something wrong? Is there another way that functions can be passed to web workers? Or is it not possible?</p>