How Web Workers Work in Chrome

Asked

Viewed 70 times

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 showing in Chrome is:

Uncaught Domexception: Failed to Construct 'Worker'

  • Shouldn’t have a tag <script> loading the file webworker.js?

  • Not Renan. It’s an external JS file. I only showed the main content there.

1 answer

1

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

Inside the folder where yours is index.html lift a running server:

php -s localhost:3000

And test the page through this address.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.