Skip to content

Commit

Permalink
fix: fix cross origin workers
Browse files Browse the repository at this point in the history
  • Loading branch information
Loïc Mangeonjean committed Jan 31, 2024
1 parent 2cf2103 commit f0a8305
Showing 1 changed file with 33 additions and 8 deletions.
41 changes: 33 additions & 8 deletions src/tools/crossOriginWorker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,39 @@
* Cross origin workers don't work
* The workaround used by vscode is to start a worker on a blob url containing a short script calling 'importScripts'
* importScripts accepts to load the code inside the blob worker
* Copied from https://github.com/jantimon/remote-web-worker/blob/main/src/index.ts
*/
class CrossOriginWorker extends Worker {
constructor (url: string | URL, options: WorkerOptions = {}) {
const fullUrl = new URL(url, window.location.href).href
const js = options.type === 'module' ? `import '${fullUrl}';` : `importScripts('${fullUrl}');`
const blob = new Blob([js], { type: 'application/javascript' })
super(URL.createObjectURL(blob), options)
export class Worker extends window.Worker {
constructor (scriptURL: string | URL, options?: WorkerOptions) {
const url = String(scriptURL)
super(
// Check if the URL is remote
url.includes('://') && !url.startsWith(location.origin)
// Launch the worker with an inline script that will use `importScripts`
// to bootstrap the actual script to work around the same origin policy.
? URL.createObjectURL(
new Blob(
[
// Replace the `importScripts` function with
// a patched version that will resolve relative URLs
// to the remote script URL.
//
// Without a patched `importScripts` Webpack 5 generated worker chunks will fail with the following error:
//
// Uncaught (in promise) DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope':
// The script at 'http://some.domain/worker.1e0e1e0e.js' failed to load.
//
// For minification, the inlined variable names are single letters:
// i = original importScripts
// a = arguments
// u = URL
`importScripts=((i)=>(...a)=>i(...a.map((u)=>''+new URL(u,"${url}"))))(importScripts);importScripts("${url}")`
],
{ type: 'text/javascript' }
)
)
: scriptURL,
options
)
}
}

export { CrossOriginWorker as Worker }

0 comments on commit f0a8305

Please sign in to comment.