问题
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