Skip to content

Instantly share code, notes, and snippets.

@ookkoouu
Last active February 20, 2024 08:19
Show Gist options
  • Save ookkoouu/0c979f8008cf491b4ea67bbd49605576 to your computer and use it in GitHub Desktop.
Save ookkoouu/0c979f8008cf491b4ea67bbd49605576 to your computer and use it in GitHub Desktop.
Dynamic UI mounting in WXT
import type {
ContentScriptContext,
ContentScriptUi,
ShadowRootContentScriptUiOptions,
} from "wxt/client";
import domObserver from "./dom-observer";
export function createShadowRootDynamicUI(
ctx: ContentScriptContext,
options: ShadowRootContentScriptUiOptions<unknown> & { anchor: string }
) {
const elementUiMap = new WeakMap<Element, ContentScriptUi<unknown>>();
const mountUI = async (elm: Element) => {
const ui = await createShadowRootUi(ctx, { ...options, anchor: elm });
elementUiMap.set(elm, ui);
ui.mount();
};
const removeUI = (elm: Element) => {
const ui = elementUiMap.get(elm);
if (ui !== undefined) {
ui.remove();
elementUiMap.delete(ui);
}
};
domObserver.added(options.anchor, mountUI);
domObserver.removed(options.anchor, removeUI);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment