1

I have written a very basic web worker, but is not working. Any help would be appreciated. Thanks.

Here's my HTML code:

<!DOCTYPE html>
<html>
<head>
    <title>Basic Demo of Web Workers</title>
</head>
<body>
    <button type="button" onclick="start()">Start!</button>
    <button type="button" onclick="stop()">Stop!</button>
    <output id="counterShow"></output> 
</body>
<script>
    var myWorker;
    function start() {
        if(window.Worker) {
            myWorker = new Worker("http://yourjavascript.com/8257018521/basic-demo.js");
            myWorker.onmessage = function(event) {
                document.getElementById('counterShow').innerHTML = event.data;
            };
            myWorker.onerror = function(event) {
                alert(event.message, event);
            }

        } else {
            document.getElementsByTagName('BODY')[0].innerHTML = 'Sorry! Web workers are not supported.';
        }
    }

    function stop() {
        myWorker.terminate();
    }
</script>

Here's the JS file that is hosted on a CDN (yourjavascript.com)

for(var i=0; i<100000; i++) {
    postMessage(i);
}

The web worker is silently failing. Please help.

shahzaibkhalid
  • 117
  • 2
  • 8
  • Have you tried inspecting your code with devtools? – John Smith Aug 17 '17 at 20:42
  • 100% a CORS issue. You cannot load web workers in the same way as normal scripts in ` – Tomáš Zato Aug 18 '17 at 07:54

3 Answers3

1

Uncaught DOMException: Failed to construct 'Worker': Script at 'http://yourjavascript.com/8257018521/basic-demo.js' cannot be accessed from origin 'null'

I believe this is due to security reason.

More info: Cross Domain Web Workers

Rex
  • 521
  • 3
  • 8
1

100% a CORS issue. You cannot load web workers in the same way as normal scripts in <script> tags. Only if remote server allows alien host origins to load their files via ajax. Not sure why, but that's the way it is. See this workaround:

https://stackoverflow.com/a/33432215/607407

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
-2

Well, I fixed it myself. I started a new project on CodePen and ran the code there, and it worked out pretty sweetly. I think the key requirement for Web Workers to run is to run them online, not locally.

shahzaibkhalid
  • 117
  • 2
  • 8
  • You can run it locally but via http (local server). If you run it via file:// it won't work (considered cross-origin as Rex mentions). –  Aug 18 '17 at 07:15