【问题标题】:Web Worker Works but generate error in consoleWeb Worker 工作但在控制台中生成错误
【发布时间】:2020-08-29 09:10:08
【问题描述】:

我创建了一个可以正常工作的 Web Worker,但是当我打开 chrome 控制台时,我看到以下错误: 未捕获的类型错误:无法在“窗口”上执行“postMessage”:需要 2 个参数,但只有 1 个存在。

这是实现worker的file.js。

    'use strict';

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

GetSummaryAsync();
setInterval(GetSummaryAsync, 15000);

谁能帮我解决这个错误?

【问题讨论】:

标签: javascript jquery html web-worker


【解决方案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 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
}

【讨论】:

  • 谢谢你传递一个对象而不是一个字符串,错误已经解决了:)
  • @JonathanLoise 它应该与传递字符串或对象无关。我猜你已经在你的 HTML 中包含了 worker.js,对吗?从 HTML 中删除像 这样的内容应该可以解决问题。
  • 请..感谢帮助者@prem。感谢 techsith 提供了一个简单明了的示例。
【解决方案2】:

看起来您正在从窗口对象而不是工作者调用方法(窗口 postMessage 需要更多参数)。你是用浏览器打开的,而不是用worker API打开的吗?

检查 example how to run and communicate with worker

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-08
    • 2020-12-13
    • 2013-06-17
    • 2010-11-17
    • 2022-09-29
    • 2016-08-20
    • 1970-01-01
    • 2019-04-11
    相关资源
    最近更新 更多