pointer-input.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. const page = (code: string) => evaluateGuest(guest, code);
  24. const before = Number(await page("document.querySelector('#counter').textContent"));
  25. for (const selector of ["#counter", "#input"]) {
  26. const local = await page(`(() => {
  27. const r = document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect();
  28. return {x: r.x + r.width / 2, y: r.y + r.height / 2};
  29. })()`);
  30. const point = await win.webContents.executeJavaScript(`(() => {
  31. const view = document.querySelector('webview');
  32. const r = view.getBoundingClientRect();
  33. const x = Math.round(r.x + ${local.x}), y = Math.round(r.y + ${local.y});
  34. return {x, y, hit: document.elementFromPoint(x, y)?.tagName};
  35. })()`);
  36. assert.equal(point.hit, "WEBVIEW", JSON.stringify(point));
  37. await clickHostPoint(win, { x: point.x, y: point.y });
  38. }
  39. assert.equal(await page("document.querySelector('#counter').textContent"), String(before + 1));
  40. assert.equal(await page("document.activeElement.id"), "input");
  41. const input = await page(`(() => {
  42. const node = document.querySelector('#input');
  43. return {value: node.value, start: node.selectionStart, end: node.selectionEnd};
  44. })()`);
  45. win.webContents.debugger.attach("1.3");
  46. try {
  47. await win.webContents.debugger.sendCommand("Input.insertText", { text: "pointer-input" });
  48. } finally {
  49. win.webContents.debugger.detach();
  50. }
  51. assert.equal(
  52. await page("document.querySelector('#input').value"),
  53. input.value.slice(0, input.start) + "pointer-input" + input.value.slice(input.end),
  54. JSON.stringify(input),
  55. );
  56. }