Load SharedWorkers from blob

This commit is contained in:
Piotr Jamróz
2024-11-19 13:05:19 +01:00
parent 3fa8df6b62
commit f62fcfffd8
2 changed files with 46 additions and 0 deletions
+6
View File
@@ -3,8 +3,10 @@ import { BaseStateReport } from 'crashme/dist/types';
import { nanoid } from 'nanoid';
import { config, createMonitoringLogger } from '@grafana/runtime';
import { CorsWorker as Worker } from 'app/core/utils/CorsWorker';
import { contextSrv } from '../services/context_srv';
import { CorsSharedWorker as SharedWorker, sharedWorkersSupported } from '../utils/CorsSharedWorker';
import { isChromePerformance, prepareContext } from './crash.utils';
@@ -30,6 +32,10 @@ interface GrafanaCrashReport extends BaseStateReport {
}
export function initializeCrashDetection() {
if (!sharedWorkersSupported()) {
return;
}
initCrashDetection<GrafanaCrashReport>({
id: nanoid(5),
+40
View File
@@ -0,0 +1,40 @@
// Almost identical to CorsWorker.ts. Main difference being it creates a SharedWorker in runtime (if it's supported bythe browser
export function sharedWorkersSupported() {
return typeof window.SharedWorker !== 'undefined';
}
class SharedWorkerNotSupported implements SharedWorker {
onerror() {}
// @ts-ignore
readonly port: MessagePort;
dispatchEvent(): boolean {
return false;
}
addEventListener(): void {}
removeEventListener(): void {}
}
const BaseSharedWorkerClass = sharedWorkersSupported() ? window.SharedWorker : SharedWorkerNotSupported;
export class CorsSharedWorker extends BaseSharedWorkerClass {
constructor(url: URL, options?: WorkerOptions) {
// by default, worker inherits HTML document's location and pathname which leads to wrong public path value
// the CorsWorkerPlugin will override it with the value based on the initial worker chunk, ie.
// initial worker chunk: http://host.com/cdn/scripts/worker-123.js
// resulting public path: http://host.com/cdn/scripts
const scriptUrl = url.toString();
const urlParts = scriptUrl.split('/');
urlParts.pop();
const scriptsBasePathUrl = `${urlParts.join('/')}/`;
const importScripts = `importScripts('${scriptUrl}');`;
const objectURL = URL.createObjectURL(
new Blob([`__webpack_worker_public_path__ = '${scriptsBasePathUrl}'; ${importScripts}`], {
type: 'application/javascript',
})
);
super(objectURL, options);
URL.revokeObjectURL(objectURL);
}
}