Skip to content

Commit

Permalink
custom sharedworker
Browse files Browse the repository at this point in the history
  • Loading branch information
mroz22 committed Feb 11, 2025
1 parent 0323c21 commit caccb62
Showing 1 changed file with 37 additions and 1 deletion.
38 changes: 37 additions & 1 deletion packages/transport/src/sessions/background-browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,42 @@ import type { Descriptor } from '../types';
import { SessionsBackground } from './background';
import { HandleMessageParams, HandleMessageResponse, SessionsBackgroundInterface } from './types';

class CustomSharedWorker extends SharedWorker {
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 {};
/**
* creating BrowserSessionsBackground initiates sessions-background for browser based environments and provides:
* - `handleMessage` which is used to send messages to sessions background
Expand All @@ -14,7 +50,7 @@ export class BrowserSessionsBackground implements SessionsBackgroundInterface {
private readonly background;

constructor(sessionsBackgroundUrl: string) {
this.background = new SharedWorker(sessionsBackgroundUrl, {
this.background = new CustomSharedWorker(sessionsBackgroundUrl, {
name: '@trezor/connect-web transport sessions worker',
});
}
Expand Down

0 comments on commit caccb62

Please sign in to comment.