Skip to content

Commit 311026f

Browse files
authored
fix: check for Blob before creating worker URL, close #4462 (#4674)
1 parent fdc3212 commit 311026f

File tree

2 files changed

+6
-6
lines changed

2 files changed

+6
-6
lines changed

packages/playground/worker/__tests__/worker.spec.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,5 +65,6 @@ if (isBuild) {
6565
expect(content).toMatch(`new SharedWorker("/assets`)
6666
// inlined
6767
expect(content).toMatch(`(window.URL||window.webkitURL).createObjectURL`)
68+
expect(content).toMatch(`window.Blob`)
6869
})
6970
}

packages/vite/src/node/plugins/worker.ts

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -75,15 +75,14 @@ export function webWorkerPlugin(config: ResolvedConfig): Plugin {
7575
const content = Buffer.from(code)
7676
if (query.inline != null) {
7777
// inline as blob data url
78-
return `const blob = new Blob([atob(\"${content.toString(
79-
'base64'
80-
)}\")], { type: 'text/javascript;charset=utf-8' });
78+
return `const encodedJs = "${content.toString('base64')}";
79+
const blob = typeof window !== "undefined" && window.Blob && new Blob([atob(encodedJs)], { type: "text/javascript;charset=utf-8" });
8180
export default function WorkerWrapper() {
82-
const objURL = (window.URL || window.webkitURL).createObjectURL(blob);
81+
const objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);
8382
try {
84-
return new Worker(objURL);
83+
return objURL ? new Worker(objURL) : new Worker("data:application/javascript;base64," + encodedJs, {type: "module"});
8584
} finally {
86-
(window.URL || window.webkitURL).revokeObjectURL(objURL);
85+
objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
8786
}
8887
}`
8988
} else {

0 commit comments

Comments
 (0)