0

Probably this is not possible but I would be glad to hear about alternatives.

I have a large JS script which I want to run in a SharedWorker, but without uploading it to a server before running (it's included in a library which I want to distribute). With Dedicated Worker I can simply make a Blob. But the Blob URL is unique and also his lifetime is tied to the lifetime of the window that creates it.

What I need is a way to create SharedWorker from a string but this worker should have a URL that any other page should be able to compute exactly. Base64 strings are limited in size, so my question is if there are any alternatives to it.

Maz
  • 63
  • 7
  • `(it's included in a library which I want to distribute).`, so some how the client has access to this, if so, why not just load directly into a service worker?. – Keith Jul 10 '23 at 16:05
  • It wouldn't be accessible by a `cdn`, but developers would be able to install it (via `npm`) – Maz Jul 10 '23 at 16:06
  • You're looking for a way to start a local server in the browser using SharedWorker, and make it persist after the window closes? – Barmar Jul 10 '23 at 16:10
  • In that case, I would say a Blob URL is the way,.. But what you could do is create a very small WebWorker with this option, and then send the large code bit via `PostMessage` to the webworker. – Keith Jul 10 '23 at 16:10
  • @keith thanks. Would you like to write it as an answer so I would be able to accept it? – Maz Jul 10 '23 at 16:17

1 Answers1

1

If you are wanting to create a WebWorker from a string, and this string could be very large. Instead of creating a very large data URI, or Blob URL. You could use that option to bootstrap a WebWorker first. Inside the WebWorker you could then wait for a message sent via postMessage that contained the large code to execute.

One thing to note: you are going to require the webWorker to then new Function or eval the code, so be aware of any XSS attack vectors. From what you are describing this sounds like it's not an issue, but I thought it might be worth pointing out.

Also just found -> How to create a Web Worker from a string That also has a fallback that uses eval so that might also help.

Ron
  • 5,900
  • 2
  • 20
  • 30
Keith
  • 22,005
  • 2
  • 27
  • 44