How Web Workers work in Chrome

0

I am using a WebWorker and locally it is not working and I am not able to find a solution.

I created a test file to illustrate here:

WebWorker.js

var i = 0;

function timedCount() {
    i = i + 1;
    postMessage(i);
    setTimeout("timedCount()",333);
}

timedCount();

HTML Page

<!DOCTYPE html>
<html>
    <body>

        <p>Count numbers: <output id="result"></output></p>
        <button onclick="startWorker()">Start Worker</button> 
        <button onclick="stopWorker()">Stop Worker</button>

        <script>

        var w;

        function startWorker() {
            if(typeof(Worker) !== "undefined") { 
                if(typeof(w) == "undefined") { 
                    w = new Worker("WebWorker.js");
                } 
            } else {
                document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Workers...";
            }

            w.onmessage = function(event) {
                    document.getElementById("result").innerHTML = event.data;
                };
        }

        function stopWorker() { 
            w.terminate();
            w = undefined;
        }

        </script>

</body>
</html>

The error you're experiencing in Chrome is:

  

Uncaught DOMException: Failed to construct 'Worker'

    
asked by anonymous 27.04.2017 / 15:07

1 answer

1

You are probably opening the file directly to the browser, correct? Chrome does not load workers from a local file ( file:// protocol).

Inside the folder where your index.html is, raise a server running:

php -s localhost:3000

And test the page through this address.

    
14.09.2018 / 12:59