Nigiri
Nigiri

Reputation: 3639

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

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

Answers (3)

Anton Panchishin
Anton Panchishin

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.

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.

Upvotes: 14

Shane Holloway
Shane Holloway

Reputation: 7852

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!)

Upvotes: 2

Bubbles
Bubbles

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

Related Questions