Web Worker可以工作但在控制台中生成错误

时间:2018-01-10 10:30:42

标签: javascript jquery html5 web-worker

我创建了一个正常工作的Web Worker但是当我打开chrome Console时,我看到以下错误: 未捕获的TypeError:无法执行' postMessage' on' Window':需要2个参数,但只有1个参数。

这是实现worker的file.js。

    'use strict';

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

GetSummaryAsync();
setInterval(GetSummaryAsync, 15000);

有人可以帮我解决错误吗?

2 个答案:

答案 0 :(得分:1)

这是webworker添加两个数字的示例,尝试以类似的方式

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 responce 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

}

答案 1 :(得分:0)

看起来你正在从window对象而不是worker调用方法(window postMessage需要更多的参数)。您是否使用浏览器而不是使用工作程序API打开它?

检查 example how to run and communicate with worker