简体   繁体   中英

Can I spawn a Web Worker and inject JavaScript functions into it from the parent “process”?

Is it possible to spawn a web worker, and somehow inject JavaScript functions into it from the parent thread? ie. without having to make the worker include a file, rather I want the parent to inject it somehow.

One option is to send the functions code through the usual channel and use the constructor new Function() (or eval() ) to recreate the function.

In both cases you should check, what is actually transmitted to prevent security risks.

main script

// your function given as arguments and code
var funktion = {
  args: ['a', 'b' ],
  source: 'return a + b;'
};

// send it to your worker
worker.postMessage( funktion );

worker

self.addEventListener( 'message', function( msg ){

  // build array for constructor arguments
  var args = [ null ].concat( fk.a, fk.c );

  // create function
  var yourFunc = new (Function.prototype.bind.apply(Function, args));

  // use yourFunc
});

This uses the dynamic use of the Function constructor as described in this answer .


Using eval() may be simpler depending on how you have the function's code:

main script

// your function given as arguments and code
var funktion = "function add(a,b){ return a + b; }";

// send it to your worker
worker.postMessage( funktion );

worker

self.addEventListener( 'message', function( msg ){      

  // create function
  var yourFunc = eval( "(function(){ return " + funktion + "; })()" );

  // use yourFunc
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM