Search code examples
javascriptwebshared

SharedWorker Not Working ...much less sharing


This post is a question which I will answer because I have searched high and low to find an answere to. Its very basic - as basic as you can get when creating a SharedWorker in JavaScript.

I came across an odd problem which has taken me hours to resolve. It was just to get a basic (really) SharedWorker to post a message to the window.

Right now, in my code I am using

...
var port = event.source
...

Everything else is pretty standard across blog articles/tutorials.

Why won't this work?


Solution

  • ANSWER:

    I had originally started off on the blog "http://net.tutsplus.com/tutorials/javascript-ajax/getting-started-with-web-workers/" to do a hello SharedWorker example. DO NOT USE THIS ARTICLE ONLY!!!

    The only problem that was holding me back was the that blog "var port = event.source" -- THIS IS INVALID!

    USE var port = event.ports[0].

    PS. Shared Workers don't have a window object so alert, console.log, etc will not work.

    Working code:

    index.html:

    `<div>
      <b>Welcome :)</b>
    </div>
    <script src="/js/main.js"></script>`
    

    main.js:

    var WorkerIO = new SharedWorker('/js/worker.io.js', 'NDN-Worker');
    
    console.log('WorkerIO:', WorkerIO);
    
    WorkerIO.port.addEventListener('message', function(eventM){
      console.log('OnMessage:', eventM);
    }, false);
    
    WorkerIO.port.start();
    WorkerIO.port.postMessage('This is a message from the client!');
    
    WorkerIO.port.addEventListener('error', function(e){
      throw new Error('WorkerIO Error: could not open SharedWorker', e);
    }, false);
    
    
    //importScripts();
    

    Worker.io.js:

    var ports = [];
    self.addEventListener('connect', function(eventC){
      'use strict';
    
      ports = eventC.ports;
      var port = ports[0];
    
      port.postMessage('WorkerIO: connected');
    
      console.log('o************ OnConnect ************o\n\n'
        , '\t ports:', ports, '\n'
        , '\t port:', port, '\n'
      );
    
      port.addEventListener('message', function(eventM){
        var data = eventM.data;
        console.log('o************ OnMessage ************o\n\n'
          , '\t data:', data, '\n'
        );
        port.postMessage('from "clientPort": ' + clientPort.toString() + ', with love :)');
      }, false);
    
      port.start();
    }, false);
    

    Happy coding:)