feat: add service worker support

This commit is contained in:
Derrick Hammer 2023-09-10 19:06:55 -04:00
parent c4e211b04c
commit 15c59603f2
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
1 changed files with 45 additions and 9 deletions

View File

@ -67,6 +67,19 @@ let nonceCounter: number;
let bgConn: any; let bgConn: any;
let serviceWorker: ServiceWorker;
let kernelIframe: HTMLIFrameElement;
async function serviceWorkerReady() {
const sw = await navigator.serviceWorker.ready;
navigator.serviceWorker.onmessage = (...args) => handleMessage(...args);
serviceWorker = sw.active as ServiceWorker;
}
function getServiceWorker() {
return serviceWorker;
}
function initNonce() { function initNonce() {
nonceSeed = new Uint8Array(16); nonceSeed = new Uint8Array(16);
nonceCounter = 0; nonceCounter = 0;
@ -117,6 +130,28 @@ function handleMessage(event: MessageEvent) {
return; return;
} }
if (event.source === kernelIframe?.contentWindow) {
if (
["response", "queryUpdate", "responseNonce", "responseUpdate"].includes(
event.data.method,
) &&
event.data.sw
) {
delete event.data.sw;
serviceWorker?.postMessage(event.data);
return;
}
}
if (event.source === serviceWorker) {
if (["moduleCall", "queryUpdate", "response"].includes(event.data.method)) {
kernelIframe?.contentWindow?.postMessage(
{ ...event.data, sw: true },
"https://kernel.lumeweb.com",
);
return;
}
}
if (IS_EXTENSION && !event.data?.data) { if (IS_EXTENSION && !event.data?.data) {
event.data.data = Object.assign({}, event.data); event.data.data = Object.assign({}, event.data);
} }
@ -249,14 +284,14 @@ function handleMessage(event: MessageEvent) {
} }
function launchKernelFrame() { function launchKernelFrame() {
const iframe = document.createElement("iframe"); kernelIframe = document.createElement("iframe");
iframe.src = "https://kernel.lumeweb.com"; kernelIframe.src = "https://kernel.lumeweb.com";
iframe.width = "0"; kernelIframe.width = "0";
iframe.height = "0"; kernelIframe.height = "0";
iframe.style.border = "0"; kernelIframe.style.border = "0";
iframe.style.position = "absolute"; kernelIframe.style.position = "absolute";
document.body.appendChild(iframe); document.body.appendChild(kernelIframe);
kernelSource = <Window>iframe.contentWindow; kernelSource = <Window>kernelIframe.contentWindow;
kernelOrigin = EXTENSION_HOSTED_ORIGIN; kernelOrigin = EXTENSION_HOSTED_ORIGIN;
kernelAuthLocation = `${EXTENSION_HOSTED_ORIGIN}/auth.html`; kernelAuthLocation = `${EXTENSION_HOSTED_ORIGIN}/auth.html`;
sourceDefer.resolve(); sourceDefer.resolve();
@ -269,7 +304,7 @@ function launchKernelFrame() {
} }
initResolved = true; initResolved = true;
initDefer.resolve( initDefer.resolve(
"tried to open kernel in iframe, but hit a timeout" as any, "tried to open kernel in kernelIframe, but hit a timeout" as any,
); );
}, 24000); }, 24000);
} }
@ -647,4 +682,5 @@ export {
loginDefer, loginDefer,
logoutDefer, logoutDefer,
newKernelQuery, newKernelQuery,
serviceWorkerReady,
}; };