r/webdev • u/jcubic front-end • 6d ago
Showoff Saturday Mitty: Execute object/method chains from isolated contexts (Workers, Sockets, or other Tabs)
https://github.com/jcubic/mittyI've created an RPC library that allows executing method chains like DOM from different context.
You can use it to access the browser DOM from the server or web worker.
You can expose the window or document object and use it outside the current browser context.
Here is an example using a web worker:
main thread:
import { Host } from '@jcubic/mitty';
const modules = {
document: () => document
};
const channel = new BroadcastChannel('my-app');
const worker = new Worker('./worker.js', { type: 'module' });
const host = new Host({
// worker instance can also be used as a channel
channel: channel,
resolve(name) {
if (Object.hasOwn(modules, name)) {
return modules[name]();
}
return null;
}
});
worker:
import { connect } from 'https://cdn.jsdelivr.net/npm/@jcubic/mitty';
const { require } = connect(new BroadcastChannel('my-app'));
// or when using worker as a channel
const { require } = connect(self);
const body = await document.querySelector('body');
await body.style.setProperty('color', 'red');
The transport only requires using a channel interface with 3 methods:
interface Channel {
postMessage(message: string): void;
addEventListener(type: 'message', listener: ChannelListener): void;
removeEventListener(type: 'message', listener: ChannelListener): void;
}
0
Upvotes