web-remote-visibility-browser.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. import { appendFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { chromium, type Page } from "playwright-core";
  4. interface LocalChromiumPage extends Page {
  5. _connection?: {
  6. toImpl?(page: Page): {
  7. delegate?: {
  8. _mainFrameSession?: {
  9. _client?: {
  10. send(method: string, params: { enabled: boolean }): Promise<void>;
  11. };
  12. };
  13. };
  14. };
  15. };
  16. }
  17. async function useNativeVisibility(page: Page) {
  18. // Playwright在主CDP session强制focus emulation,使后台tab也永远visible。
  19. // 新CDP session不能撤销原session的覆盖;只关闭本地driver原始session的测试仿真,
  20. // 后续完全使用Chrome真实tab切换,不修改document getter或派发visibility事件。
  21. const local = page as LocalChromiumPage;
  22. const client = local._connection?.toImpl?.(page)?.delegate?._mainFrameSession?._client;
  23. if (typeof client?.send !== "function")
  24. throw new Error(
  25. "MRO03: Playwright local Chromium visibility ABI changed; native visibility is required",
  26. );
  27. await client.send("Emulation.setFocusEmulationEnabled", { enabled: false });
  28. }
  29. /** 使用成熟导航与清理流程,仅撤销测试框架强制前台;浏览器仍是真实headed Chrome。 */
  30. export async function createWebRemoteVisibilityBrowser(artifactDir: string) {
  31. const executablePath =
  32. process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE || process.env.R3_MOBILE_CHROME;
  33. const chrome = await chromium.launch({
  34. ...(executablePath ? { executablePath } : { channel: "chrome" }),
  35. headless: false,
  36. });
  37. const context = await chrome.newContext({
  38. viewport: { width: 1440, height: 1000 },
  39. locale: "zh-CN",
  40. });
  41. const page = await context.newPage();
  42. page.setDefaultTimeout(30_000);
  43. let logFlight = Promise.resolve();
  44. const recordEvent = (stage: string, detail?: unknown) => {
  45. logFlight = logFlight.then(() =>
  46. appendFile(
  47. join(artifactDir, "MRO03-native-stages.jsonl"),
  48. JSON.stringify({ stage, detail }) + "\n",
  49. ),
  50. );
  51. return logFlight;
  52. };
  53. const record = async (stage: string) =>
  54. recordEvent(stage, {
  55. visibility: await page.evaluate(() => document.visibilityState),
  56. });
  57. page.on("framenavigated", (frame) => {
  58. if (frame === page.mainFrame())
  59. void recordEvent("main-frame-navigated", { path: new URL(frame.url()).pathname });
  60. });
  61. page.on("request", (request) => {
  62. if (request.isNavigationRequest() && request.frame() === page.mainFrame())
  63. void recordEvent("document-request", { path: new URL(request.url()).pathname });
  64. });
  65. page.on("console", (message) => {
  66. if (message.text().startsWith("[vite]"))
  67. void recordEvent("vite-client", {
  68. text: message.text().replace(/https?:\/\/[^\s]+/gu, "<url>"),
  69. });
  70. });
  71. page.on("crash", () => {
  72. void recordEvent("page-crashed");
  73. });
  74. page.on("close", () => {
  75. void recordEvent("page-closed");
  76. });
  77. let cover: Page | undefined;
  78. return {
  79. evaluate: <T>(expression: string) => page.evaluate<T, void>(expression, undefined),
  80. async navigate(url: string, credentials: Record<string, string>) {
  81. await context.addInitScript((values) => {
  82. if (!location.protocol.startsWith("http")) return;
  83. for (const [key, value] of Object.entries(values)) localStorage.setItem(key, value);
  84. }, credentials);
  85. await page.goto(url, { waitUntil: "domcontentloaded", timeout: 60_000 });
  86. await useNativeVisibility(page);
  87. await page.bringToFront();
  88. await record("native-navigation");
  89. },
  90. async click(selector: string) {
  91. await page.locator(selector).first().click();
  92. },
  93. async hide() {
  94. cover ??= await context.newPage();
  95. await useNativeVisibility(cover);
  96. await cover.bringToFront();
  97. await page.waitForFunction(() => document.visibilityState === "hidden");
  98. await record("native-background");
  99. },
  100. async show() {
  101. await page.bringToFront();
  102. await page.waitForFunction(() => document.visibilityState === "visible");
  103. await record("native-foreground");
  104. },
  105. async escape() {
  106. await page.keyboard.press("Escape");
  107. },
  108. async screenshot(name: string) {
  109. await page.screenshot({ path: join(artifactDir, name) });
  110. },
  111. async close() {
  112. await context.close();
  113. await chrome.close();
  114. await logFlight;
  115. },
  116. };
  117. }