Skip to content

Commit a02c4e7

Browse files
committed
Add built-in support for cross-origin web worker loading
1 parent c1ec8af commit a02c4e7

1 file changed

Lines changed: 16 additions & 1 deletion

File tree

src/vs/base/worker/defaultWorkerFactory.ts

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,22 @@ function getWorker(workerId: string, label: string): Worker | Promise<Worker> {
1818
}
1919
// ESM-comment-begin
2020
if (typeof require === 'function') {
21-
return new Worker(require.toUrl('./' + workerId) + '#' + label);
21+
// check if the JS lives on a different origin
22+
23+
const workerMain = require.toUrl('./' + workerId);
24+
if (/^(http:)|(https:)|(file:)/.test(workerMain)) {
25+
const currentUrl = String(window.location);
26+
const currentOrigin = currentUrl.substr(0, currentUrl.length - window.location.hash.length - window.location.search.length - window.location.pathname.length);
27+
if (workerMain.substring(0, currentOrigin.length) !== currentOrigin) {
28+
// this is the cross-origin case
29+
// i.e. the webpage is running at a different origin than where the scripts are loaded from
30+
const workerBaseUrl = workerMain.substr(0, workerMain.length - 'vs/base/worker/workerMain.js'.length);
31+
const js = `/*${label}*/self.MonacoEnvironment={baseUrl: '${workerBaseUrl}'};importScripts('${workerMain}');/*${label}*/`;
32+
const url = `data:text/javascript;charset=utf-8,${encodeURIComponent(js)}`;
33+
return new Worker(url);
34+
}
35+
}
36+
return new Worker(workerMain + '#' + label);
2237
}
2338
// ESM-comment-end
2439
throw new Error(`You must define a function MonacoEnvironment.getWorkerUrl or MonacoEnvironment.getWorker`);

0 commit comments

Comments
 (0)