javascript web workers - 我如何传递参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4019230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:09:22  来源:igfitidea点击:

javascript web workers - how do I pass arguments?

javascript

提问by Joe

Found the answer some some of my problems, html5 web workers!!!

找到了我的一些问题的答案,html5 网络工作者!!!

How do I pass an argument to a web worker though using this basic example?

尽管使用这个基本示例,我如何将参数传递给网络工作者?

contents of worker.js:

worker.js 的内容:

function doSomething() {
    postMessage( ' done');
}
setTimeout ( "doSomething()", 3000 );

js code:

js代码:

 var worker = new Worker('worker.js');
  worker.onmessage = function (event) {
    alert(event.data);
  };

回答by ?ime Vidas

As you can see you have the same mechanism for both worker-to-main and main-to-worker messages.

如您所见,对于 worker-to-main 和 main-to-worker 消息,您具有相同的机制。

  • the postMessagemethod for sending messages
  • the onmessagemember for defining the handler that receives the messages
  • postMessage发送消息的方法
  • onmessage用于定义接收消息的处理程序的成员

In the main script:

在主脚本中:

worker.postMessage(data);

In the worker script:

在工作脚本中:

self.addEventListener("message", function(e) {
    // the passed-in data is available via e.data
}, false);

... or just...

... 要不就...

onmessage = function(e) {
    // the passed-in data is available via e.data
};

It may be that data has to be a string... (Firefox 3.5+ supports passing in JSON-compatible objects)

可能数据必须是字符串...(Firefox 3.5+ 支持传入与 JSON 兼容的对象)

回答by Jozcar

 var worker = new Worker(window.App.baseUrl + '/Scripts/signature/GetCurrenProductWorker.js');
                    worker.postMessage(window.App.baseUrl)


    var _base_url = ''
        var xhr = new XMLHttpRequest();
        onmessage = function (e) {
            _base_url = e.data
            xhr.open("GET", _base_url + "/api/product/Get");
            xhr.onload = function () {
                postMessage(xhr.responseText);
            };
            xhr.send();

        };

this work for me

这对我有用