Can I pass parameters to .js function when I create the new Web Workers object?

痴心易碎 提交于 2020-01-23 06:29:46

问题


When I create a web workers like the following...

 var w = new Worker("./Scripts/sample.js");

sample.js want to some parameters from the caller!!
Possible?


回答1:


I haven't used web workers a whole bunch, but per this description I believe you could do it along these lines:

var worker = new Worker("sample.js");
worker.postMessage({ "args": [ ] });

Then, in sample.js, structure it along these lines:

self.addEventListener("message", function(e) {
  var args = e.data.args;
  // do whatever you need with the arguments
}, false);

This isn't quite the same as a traditional argument passing, as whatever goes in postMessage must be formattable as a JSON (e.g. no functions). But, there's a decent chance it can be made to do what you need it to do.




回答2:


2018-July

location is available in WebWorkers (according to MDN), which opens up location.hash, location.search, and even location.pathname as ways of passing information. (Tested on Mac OSX in Chrome, Safari, FireFox)

Also, hash and query arguments worked in Chrome and FireFox for URL.createObjectURL(Blob([src])), but not Safari.

(Apologies for the necroposting; search results are forever!)




回答3:


Question

How can I pass parameters sample.js when using it as a web working like this var w = new Worker("./Scripts/sample.js"); ?

Answer

You can pass arguments in the query string and in sample.js get the arguments from location.search. You do not need to call postMessage to accomplish this.

Example Code

Calling code would be

var w = new Worker("./Scripts/sample.js?answer=42&question=ultimate");

This will call the worker. In sample.js location.search will equal ?answer=42&question=ultimate. We can use the following code to pull it out gracefully

var parameters = {}
location.search.slice(1).split("&").forEach( function(key_value) { var kv = key_value.split("="); parameters[kv[0]] = kv[1]; })

var question = parameters['question'];
var answer = parameters['answer'];

Live Example

You can see a live example here

Final Thoughts

If you have a large amount of data to send, don't use the query string.



来源:https://stackoverflow.com/questions/12381882/can-i-pass-parameters-to-js-function-when-i-create-the-new-web-workers-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!