Skip to content

Commit

Permalink
fix: Add worker loading fallback
Browse files Browse the repository at this point in the history
  • Loading branch information
3y3 committed Sep 27, 2024
1 parent bfb7e5c commit c6d8ef8
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
28 changes: 23 additions & 5 deletions src/components/Search/provider/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,19 +43,37 @@ export class SearchProvider implements ISearchProvider {
// };

private get base() {
return window.location.pathname
.split('/')
.slice(0, -(this.config.depth + 1))
.join('/');
return window.location.href.split('/').slice(0, -this.config.depth).join('/');
}

private async request(message: object) {
return request(await this.worker, message);
}
}

const BAD_ORIGIN_ERROR = /Script at '(.*?)' cannot be accessed from origin/;

async function loadWorker() {
try {
return new Worker(new URL('../worker/index.ts', import.meta.url));
} catch (error) {
// @see https://stackoverflow.com/questions/21408510/chrome-cant-load-web-worker
if (error instanceof DOMException) {
const match = BAD_ORIGIN_ERROR.exec(error.message);
if (match) {
const url = match[1];
const blob = new Blob([`importScripts('${url}');`], {type: 'text/javascript'});

return new Worker(URL.createObjectURL(blob));
}
}

throw error;
}
}

async function initWorker(config: WorkerConfig) {
const worker = new Worker(new URL('../worker/index.ts', import.meta.url));
const worker = await loadWorker();

await request(worker, {...config, type: 'init'});

Expand Down
2 changes: 1 addition & 1 deletion src/components/Search/worker/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const HANDLERS = {
async init(config: InitMessage) {
self.config = config;

importScripts(self.config.api);
importScripts(self.config.base + '/' + self.config.api);

AssertApi(self.api);

Expand Down

0 comments on commit c6d8ef8

Please sign in to comment.