pointer-input.ts 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import assert from "node:assert/strict";
  2. import type { BrowserWindow, WebContents } from "electron";
  3. import { evaluateGuest } from "./guest-evaluation.js";
  4. /** 从宿主坐标发送鼠标事件,避免直接向 guest 注入点击绕过透明层命中测试。 */
  5. export async function clickHostPoint(win: BrowserWindow, point: { x: number; y: number }) {
  6. win.webContents.debugger.attach("1.3");
  7. try {
  8. for (const type of ["mousePressed", "mouseReleased"])
  9. await win.webContents.debugger.sendCommand("Input.dispatchMouseEvent", {
  10. type,
  11. ...point,
  12. button: "left",
  13. clickCount: 1,
  14. });
  15. await win.webContents.executeJavaScript(
  16. "new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))",
  17. );
  18. } finally {
  19. win.webContents.debugger.detach();
  20. }
  21. }
  22. export async function checkPagePointerInput(win: BrowserWindow, guest: WebContents) {
  23. // 握手完成不等于首帧已合成;能力裁决后 guest 才从后台迁入展示位置。
  24. // 先等布局进入绘制,再发宿主坐标事件,避免首个点击仍命中旧的合成区域。
  25. await win.webContents.executeJavaScript(
  26. "new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))",
  27. );
  28. const page = (code: string) => evaluateGuest(guest, code);
  29. const before = Number(await page("document.querySelector('#counter').textContent"));
  30. for (const selector of ["#counter", "#input"]) {
  31. const local = await page(`(() => {
  32. const r = document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect();
  33. return {x: r.x + r.width / 2, y: r.y + r.height / 2};
  34. })()`);
  35. const point = await win.webContents.executeJavaScript(`(() => {
  36. const view = document.querySelector('webview');
  37. const r = view.getBoundingClientRect();
  38. const x = Math.round(r.x + ${local.x}), y = Math.round(r.y + ${local.y});
  39. return {x, y, hit: document.elementFromPoint(x, y)?.tagName};
  40. })()`);
  41. assert.equal(point.hit, "WEBVIEW", JSON.stringify(point));
  42. await clickHostPoint(win, { x: point.x, y: point.y });
  43. }
  44. assert.equal(await page("document.querySelector('#counter').textContent"), String(before + 1));
  45. assert.equal(await page("document.activeElement.id"), "input");
  46. const input = await page(`(() => {
  47. const node = document.querySelector('#input');
  48. return {value: node.value, start: node.selectionStart, end: node.selectionEnd};
  49. })()`);
  50. win.webContents.debugger.attach("1.3");
  51. try {
  52. await win.webContents.debugger.sendCommand("Input.insertText", { text: "pointer-input" });
  53. } finally {
  54. win.webContents.debugger.detach();
  55. }
  56. assert.equal(
  57. await page("document.querySelector('#input').value"),
  58. input.value.slice(0, input.start) + "pointer-input" + input.value.slice(input.end),
  59. JSON.stringify(input),
  60. );
  61. }