Search code examples
javascriptjqueryhtmlweb-worker

Web Worker Works but generate error in console


I created a Web Worker which works correctly but when I open the chrome Console I see the following error: Uncaught TypeError: Failed to execute 'postMessage' on 'Window': 2 arguments required, but only 1 present.

This is the file.js which implements the worker.

    'use strict';

function GetSummaryAsync() {
    //$.getJSON("/api/Summary/GetSummaryAsync", function (response) {
    //    postMessage(response);
    //});
    postMessage('pippo');
}

GetSummaryAsync();
setInterval(GetSummaryAsync, 15000);

Can someone help me to solve the error?


Solution

  • This is an example of webworker to add two number, try in similar way

    worker.html

    <html>
    <script>
        if (window.Worker){
        
            var myWorker = new Worker("worker.js"); // create a worker object 
            var message = {addData: {num1: 1, num2 :5}};
            myWorker.postMessage(message) // send message to worker
            
            myWorker.onmessage = function(e){
                alert (e.data.result);
            }  // get the response from the worker
        
        }
        else {
            alert("your browser do not support");
        }
    </script>
    

    worker.js

    this.onmessage = function(e) {
      this.postMessage({result: e.data.addData.num1 + e.data.addData.num1 })  
      // add two number and send to html file
    }