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

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.


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


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.