Search code examples
javascripthtmlworker

JavaScript can't get past SharedWorker() constructor


I'm doing some research about the HTML5 Web Worker. I got the 'normal' worker running nicely, however I can't seem to initialize a SharedWorker. I've tried in the latest versions of Chrome and Firefox, without any success... Even when I run an online demo, I get no output.

For example, when I open the following document:

index.html:

<!DOCTYPE html>
<html>
    <head>
        <title>Web workers</title>
    </head>
    <body>
        <p id="log">Log:</p>
        <script>
          alert("alert 1");
          var worker = new SharedWorker("task.js");
          alert("alert 2");
          var log = document.getElementById("log");
          worker.port.addEventListener("message", function(e){
              log.textContent += "\n" + e.data;
          }, false);
          worker.port.start();
          worker.port.postMessage("ping");
        </script>
    </body>
</html>

task.js:

onconnect = function(e) {
    var port = e.ports[0];
    port.postMessage("Hello World");
    port.onmessage = function(e) {
        port.postMessage("pong");
    }
}

I added the two alert functions for debugging purposes. "alert 1" is always shown, "alert 2" is never shown, so I think that the crash happens in the SharedWorker constructor (no, it's not due to do my browser pop-up settings). Any help or advice is very welcome!


Solution

  • Thanks to robertc's tip about checking the console, I got the following error:

    Uncaught Error: SECURITY_ERR: DOM Exception 18 
    

    Google lead me to this topic, which basically tells you to run it on a web server (I used wampserver) and this helped in my case. Thanks!