javascripthtmlshared-worker

Javascript SharedWorker is not communicating properly with the main program


I've worked with Worker objects before, and it's pretty straightforward, especially with the tutorial.

So naturally the next step would be to work with SharedWorkers. I've got it down, but now it seems the SharedWorker is not responding correctly. I send a postMessage to the SharedWorker, and in my code I have the SharedWorker posting back the same text, kind of like an echo effect.

Unfortunately the SharedWorker only returns the first letter of the message sent from the main program, and does not log to the console the "Background" string to let me know the SharedWorker is running. Also the "Setup complete" log message proves that the SharedWorker was created.

Code...

The main HTML file...

<html>
<head>
<title>Test</title>
</head>
<body>
<script>
var w = new SharedWorker('sharedworker.js');
w.port.start();
w.port.postMessage("start");
w.port.onmessage = function(e){
  console.log(e.data);
}; 
console.log("Setup complete.");
</script>
</body>
</html>

The SharedWorker script...

onconnect = function(e){
  var port = e.ports[0];
  port.addEventListener('message', function(e){
    port.postMessage(e.data[0]);
  });
  port.start();
  console.log("Background.");
}

What am I doing wrong?


Solution

  • Unfortunately the SharedWorker only returns the first letter of the message sent from the main program

    Drop the [0] on the reference to the string being read. Currently it's interfacing the string as an array and only returning the first character.

    port.postMessage(e.data); // versus  port.postMessage(e.data[0]);
    

    and does not log to the console the "Background" string to let me know the SharedWorker is running

    I'm no expert, but I'll take a guess. (I can't see anything obvious in the documentation to back this up, and I've not used SharedWorkers myself before.) From a multi-processing standpoint, this is what I'd expect SharedWorkers to do - the context of the SharedWorker is completely separate, console doesn't exist in its scope.

    There's some possibly helpful answers on another SO thread regarding debugging that might help you with debugging going forward: How to debug web workers