Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create worker from data URI

I have a very simple need, I need to spawn a webworker with a small data uri script:

new Worker('data:,console.log("HI")');

In Firefox this is giving me instead an error. Error is:

 SecurityError: Failed to load worker script at "data:,console.log("HI")"

Is there anyway to get worker to work with data URI?

like image 771
Noitidart Avatar asked Aug 10 '26 05:08

Noitidart


2 Answers

You could definitely try Freelancer which:

  • Takes a function that it transforms to a string using Function.prototype.toString
  • Creates an IIFE from the passed function and passes in any additional arguments
  • Transforms the function into a Blob with application/javascript as the type
  • Instantiates the new worker with the data URI created with URL.createObjectURL.
like image 136
Wildhoney Avatar answered Aug 12 '26 19:08

Wildhoney


Freelancer is equivalent to these 5 lines of code (if you don't care about error messages when your browser doesn't support Web Workers).

class Worker extends globalThis.Worker {
    constructor(fn, ...params) {
        return super(URL.createObjectURL(new Blob([`(${fn.toString()})(${params.map(JSON.stringify)})`], {type: 'application/javascript'})))
    }
}
like image 26
timkay Avatar answered Aug 12 '26 17:08

timkay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!