feat: implement a simple dynamic message system from the background script to the bootloader/kernel
This commit is contained in:
parent
76fabec96a
commit
f3f0a8374a
|
@ -13,4 +13,28 @@ browser.runtime.onInstalled.addListener(() => {
|
|||
});
|
||||
});
|
||||
|
||||
browser.runtime.onMessage.addListener(async (request, sender) => {
|
||||
if (sender.id !== browser.runtime.id) {
|
||||
return Promise.reject("access denied");
|
||||
}
|
||||
|
||||
if (!("method" in request)) {
|
||||
return Promise.reject("method required");
|
||||
}
|
||||
if (!("data" in request)) {
|
||||
return Promise.reject("data required");
|
||||
}
|
||||
|
||||
const ret = await queryKernel({
|
||||
method: request.method,
|
||||
data: request.data,
|
||||
});
|
||||
|
||||
if (ret?.err) {
|
||||
throw new Error(ret.err);
|
||||
}
|
||||
|
||||
return ret;
|
||||
});
|
||||
|
||||
boot();
|
||||
|
|
|
@ -1,4 +1,6 @@
|
|||
import { boot } from "./bootloader/kernel.js";
|
||||
import exchangeCommunicationKeys from "./bootloader/messages/exchangeCommunicationKeys.js";
|
||||
import setLoginKey from "./bootloader/messages/setLoginKey.js";
|
||||
|
||||
declare var browser: any; // tsc
|
||||
|
||||
|
@ -8,7 +10,12 @@ header.textContent =
|
|||
"Something went wrong! You should not be visiting this page, this page should only be accessed via an invisible iframe.";
|
||||
document.body.appendChild(header);
|
||||
|
||||
function handleIncomingMessage(event: MessageEvent) {
|
||||
const kernelMessageHandlers = {
|
||||
exchangeCommunicationKeys,
|
||||
setLoginKey,
|
||||
};
|
||||
|
||||
async function handleIncomingMessage(event: MessageEvent) {
|
||||
if (event.source === null) {
|
||||
return;
|
||||
}
|
||||
|
@ -39,6 +46,28 @@ function handleIncomingMessage(event: MessageEvent) {
|
|||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.data.method in kernelMessageHandlers) {
|
||||
let response;
|
||||
|
||||
try {
|
||||
response = await kernelMessageHandlers[event.data.method](
|
||||
event.data.data,
|
||||
);
|
||||
} catch (e: any) {
|
||||
response = { err: (e as Error).message };
|
||||
}
|
||||
|
||||
(event.source as WindowProxy).postMessage(
|
||||
{
|
||||
nonce: event.data.nonce,
|
||||
data: response,
|
||||
},
|
||||
event.origin,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
(event.source as WindowProxy).postMessage(
|
||||
{
|
||||
nonce: event.data.nonce,
|
||||
|
|
Reference in New Issue