|
2 | 2 | * Cross origin workers don't work |
3 | 3 | * The workaround used by vscode is to start a worker on a blob url containing a short script calling 'importScripts' |
4 | 4 | * importScripts accepts to load the code inside the blob worker |
| 5 | + * Copied from https://github.com/jantimon/remote-web-worker/blob/main/src/index.ts |
5 | 6 | */ |
6 | | -class CrossOriginWorker extends Worker { |
7 | | - constructor (url: string | URL, options: WorkerOptions = {}) { |
8 | | - const fullUrl = new URL(url, window.location.href).href |
9 | | - const js = options.type === 'module' ? `import '${fullUrl}';` : `importScripts('${fullUrl}');` |
10 | | - const blob = new Blob([js], { type: 'application/javascript' }) |
11 | | - super(URL.createObjectURL(blob), options) |
| 7 | +export class Worker extends window.Worker { |
| 8 | + constructor (scriptURL: string | URL, options?: WorkerOptions) { |
| 9 | + const url = String(scriptURL) |
| 10 | + super( |
| 11 | + // Check if the URL is remote |
| 12 | + url.includes('://') && !url.startsWith(location.origin) |
| 13 | + // Launch the worker with an inline script that will use `importScripts` |
| 14 | + // to bootstrap the actual script to work around the same origin policy. |
| 15 | + ? URL.createObjectURL( |
| 16 | + new Blob( |
| 17 | + [ |
| 18 | + // Replace the `importScripts` function with |
| 19 | + // a patched version that will resolve relative URLs |
| 20 | + // to the remote script URL. |
| 21 | + // |
| 22 | + // Without a patched `importScripts` Webpack 5 generated worker chunks will fail with the following error: |
| 23 | + // |
| 24 | + // Uncaught (in promise) DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': |
| 25 | + // The script at 'http://some.domain/worker.1e0e1e0e.js' failed to load. |
| 26 | + // |
| 27 | + // For minification, the inlined variable names are single letters: |
| 28 | + // i = original importScripts |
| 29 | + // a = arguments |
| 30 | + // u = URL |
| 31 | + `importScripts=((i)=>(...a)=>i(...a.map((u)=>''+new URL(u,"${url}"))))(importScripts);importScripts("${url}")` |
| 32 | + ], |
| 33 | + { type: 'text/javascript' } |
| 34 | + ) |
| 35 | + ) |
| 36 | + : scriptURL, |
| 37 | + options |
| 38 | + ) |
12 | 39 | } |
13 | 40 | } |
14 | | - |
15 | | -export { CrossOriginWorker as Worker } |
|
0 commit comments