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?
Limitations of Web Workers worker. postMessage({ string: 'string', number: 0, array: [], ... }); Those value types above can be handled by the structured cloning. However, you cannot send in functions because they can be neither cloned nor transferred.
Limitations Of Web WorkersA worker can't directly manipulate the DOM and has limited access to methods and properties of the window object. A worker can not be run directly from the filesystem. It can only be run via a server.
You need to use the postMessage() method in the onmessage event handler in worker. js : // src/worker. js onmessage = e => { const message = e.
You can run whatever code you like inside the worker thread, with some exceptions. For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the window 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With