Reputation: 3639
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?
Upvotes: 10
Views: 10696
Reputation: 3773
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.
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'];
You can see a live example here
If you have a large amount of data to send, don't use the query string.
Upvotes: 14
Reputation: 7852
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!)
Upvotes: 2
Reputation: 3815
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.
Upvotes: 15