Open History to see the last commit
1// CDP input follows shared window focus; send directly to unfocused guests to avoid typing into the app.
2
3const FOCUS_ROUTED_INPUT = new Set([
4 "Input.insertText",
5 "Input.dispatchKeyEvent",
6 "Input.imeSetComposition",
7]);
8
9/** Direct input reaches only the main-frame process; insertText crashes when a cross-site frame has focus. */
10const FOCUSED_DOCUMENT = `(() => {
11 let doc = document;
12 for (;;) {
13 const active = doc.activeElement;
14 if (active?.tagName !== "IFRAME" && active?.tagName !== "FRAME") return doc;
15 if (!active.contentDocument) return null;
16 doc = active.contentDocument;
17 }
18})()`;
19
20/** Electron runs editing commands only for CDP keys; exclude clipboard commands to preserve the user's clipboard. */
21const EDITING_COMMANDS = new Set(["selectAll", "undo", "redo"]);
22
23const CROSS_SITE_FOCUS_MESSAGE =
24 "The page's focus is inside a cross-site frame, which takes typed input only while the preview has focus. Click the field first.";
25
26const ARROW_KEYS: Record<string, string> = {
27 ArrowUp: "Up",
28 ArrowDown: "Down",
29 ArrowLeft: "Left",
30 ArrowRight: "Right",
31};
32const NAMED_KEYS = new Set([
33 "Backspace",
34 "Tab",
35 "Enter",
36 "Escape",
37 "Delete",
38 "Insert",
39 "Home",
40 "End",
41 "PageUp",
42 "PageDown",
43 "Shift",
44 "Control",
45 "Alt",
46 "Meta",
47 "CapsLock",
48 "NumLock",
49 "ScrollLock",
50 "PrintScreen",
51]);
52const MODIFIER_BITS = [
53 [1, "alt"],
54 [2, "control"],
55 [4, "meta"],
56 [8, "shift"],
57] as const;
58
59const keyCodeFor = (key: string) => {
60 if ([...key].length === 1) return key;
61 if (ARROW_KEYS[key]) return ARROW_KEYS[key];
62 return NAMED_KEYS.has(key) || /^F(?:[1-9]|1\d|2[0-4])$/u.test(key) ? key : null;
63};
64
65/** Electron derives text from keyCode, so typed text needs separate char events. */
66export const toKeyboardInputEvents = (
67 params: Record<string, unknown>,
68): Array<Electron.KeyboardInputEvent> => {
69 const bits = typeof params["modifiers"] === "number" ? params["modifiers"] : 0;
70 const modifiers = MODIFIER_BITS.flatMap(([bit, name]) => (bits & bit ? [name] : []));
71 const text = typeof params["text"] === "string" ? params["text"] : "";
72 const chars = [...text].map((char) => ({ type: "char" as const, keyCode: char, modifiers }));
73 const keyCode = keyCodeFor(typeof params["key"] === "string" ? params["key"] : "");
74 switch (params["type"]) {
75 case "keyDown":
76 return [...(keyCode ? [{ type: "rawKeyDown" as const, keyCode, modifiers }] : []), ...chars];
77 case "rawKeyDown":
78 case "keyUp":
79 return keyCode ? [{ type: params["type"], keyCode, modifiers }] : [];
80 case "char":
81 return chars;
82 default:
83 return [];
84 }
85};
86
87const evaluate = async (debuggee: Electron.Debugger, expression: string) => {
88 const reply = (await debuggee.sendCommand("Runtime.evaluate", {
89 expression,
90 returnByValue: true,
91 })) as { readonly result?: { readonly value?: unknown } };
92 return reply.result?.value;
93};
94
95/** Sends one command to the guest's page, keeping reloads and input inside it. */
96export const sendPageCommand = async (
97 webContents: Electron.WebContents,
98 debuggee: Electron.Debugger,
99 method: string,
100 params: Record<string, unknown>,
101): Promise<unknown> => {
102 // Electron's debugger routes Page.reload on a webview to its embedder window.
103 if (method === "Page.reload") {
104 if (params["ignoreCache"] === true) webContents.reloadIgnoringCache();
105 else webContents.reload();
106 return {};
107 }
108 if (!FOCUS_ROUTED_INPUT.has(method) || webContents.focusedFrame) {
109 return debuggee.sendCommand(method, params);
110 }
111 if ((await evaluate(debuggee, `${FOCUSED_DOCUMENT} !== null`)) !== true) {
112 throw new Error(CROSS_SITE_FOCUS_MESSAGE);
113 }
114 switch (method) {
115 case "Input.insertText":
116 await webContents.insertText(typeof params["text"] === "string" ? params["text"] : "");
117 return {};
118 case "Input.dispatchKeyEvent": {
119 for (const event of toKeyboardInputEvents(params)) webContents.sendInputEvent(event);
120 const commands = Array.isArray(params["commands"])
121 ? params["commands"].filter((command) => EDITING_COMMANDS.has(command))
122 : [];
123 // Runs after the page handles the keys, so the reply also waits for them.
124 await evaluate(
125 debuggee,
126 `(() => { const doc = ${FOCUSED_DOCUMENT}; for (const name of ${JSON.stringify(commands)}) doc?.execCommand(name); return 0; })()`,
127 );
128 return {};
129 }
130 default:
131 throw new Error(`${method} needs the preview to have focus.`);
132 }
133};