browser-hidden-guest-screenshot-smoke.mjs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import { app, BrowserWindow, webContents } from "electron";
  2. const CAPTURE_TIMEOUT_MS = 4_000;
  3. const ACTIVITY_CAPTURE_RECT = { x: 0, y: 0, width: 1, height: 1 };
  4. function wait(timeoutMs) {
  5. return new Promise((resolve) => setTimeout(resolve, timeoutMs));
  6. }
  7. function dataUrl(html) {
  8. return `data:text/html;base64,${Buffer.from(html).toString("base64")}`;
  9. }
  10. function hostPageHtml(guestUrl) {
  11. return `<!doctype html>
  12. <html>
  13. <body>
  14. <script>
  15. window.createHiddenGuest = () => {
  16. const guest = document.createElement("webview");
  17. guest.src = ${JSON.stringify(guestUrl)};
  18. guest.style.cssText = "display:block;width:320px;height:200px";
  19. document.body.appendChild(guest);
  20. };
  21. </script>
  22. </body>
  23. </html>`;
  24. }
  25. function captureWithTimeout(contents, rect, label) {
  26. return Promise.race([
  27. contents.capturePage(rect),
  28. wait(CAPTURE_TIMEOUT_MS).then(() => {
  29. throw new Error(`${label} timed out after ${CAPTURE_TIMEOUT_MS}ms`);
  30. }),
  31. ]);
  32. }
  33. async function run() {
  34. let win;
  35. let originalOpacity;
  36. let taskbarHidden = false;
  37. let exitCode = 0;
  38. try {
  39. await app.whenReady();
  40. if (process.platform !== "darwin" && process.platform !== "win32") {
  41. console.log(
  42. JSON.stringify({
  43. skipped: `transparent hidden-window bootstrap is unsupported on ${process.platform}`,
  44. }),
  45. );
  46. return;
  47. }
  48. const guestUrl = dataUrl(`<!doctype html>
  49. <html>
  50. <body style="margin:0;background:rgb(20,90,170);width:100vw;height:100vh"></body>
  51. </html>`);
  52. win = new BrowserWindow({
  53. width: 480,
  54. height: 320,
  55. show: true,
  56. webPreferences: { webviewTag: true },
  57. });
  58. await win.loadURL(dataUrl(hostPageHtml(guestUrl)));
  59. win.hide();
  60. await wait(200);
  61. const attached = new Promise((resolve) => {
  62. win.webContents.once("did-attach-webview", (_event, guest) => resolve(guest.id));
  63. });
  64. await win.webContents.executeJavaScript("window.createHiddenGuest()", true);
  65. const guestId = await Promise.race([
  66. attached,
  67. wait(CAPTURE_TIMEOUT_MS).then(() => {
  68. throw new Error("hidden-born guest did not attach");
  69. }),
  70. ]);
  71. const guest = webContents.fromId(guestId);
  72. if (!guest || guest.hostWebContents?.id !== win.webContents.id) {
  73. throw new Error(`hidden-born guest owner mismatch: ${guestId}`);
  74. }
  75. await guest.executeJavaScript("document.readyState", true);
  76. originalOpacity = win.getOpacity();
  77. if (process.platform === "win32") {
  78. win.setSkipTaskbar(true);
  79. taskbarHidden = true;
  80. }
  81. win.setOpacity(0);
  82. win.showInactive();
  83. if (win.isFocused()) {
  84. throw new Error("transparent bootstrap unexpectedly focused the owner window");
  85. }
  86. // 与 controller 一致:先给 Viz 一个有界 presentation grace,再为 owner/guest
  87. // 各建立两份重叠 capturer;同一 turn 立即 capture 会触发 UnknownVizError。
  88. await wait(100);
  89. const bootstrapImages = await Promise.all([
  90. captureWithTimeout(win.webContents, ACTIVITY_CAPTURE_RECT, "owner bootstrap capture A"),
  91. captureWithTimeout(win.webContents, ACTIVITY_CAPTURE_RECT, "owner bootstrap capture B"),
  92. captureWithTimeout(guest, ACTIVITY_CAPTURE_RECT, "guest bootstrap capture A"),
  93. captureWithTimeout(guest, ACTIVITY_CAPTURE_RECT, "guest bootstrap capture B"),
  94. ]);
  95. if (bootstrapImages.some((image) => image.isEmpty())) {
  96. throw new Error(
  97. `hidden-born bootstrap returned empty image: ${JSON.stringify(
  98. bootstrapImages.map((image) => image.getSize()),
  99. )}`,
  100. );
  101. }
  102. // 真实产品在 renderer 两帧稳定 Ready 后执行 markPrepared;模拟该边界再恢复 hidden。
  103. await wait(50);
  104. win.hide();
  105. win.setOpacity(originalOpacity);
  106. if (taskbarHidden) {
  107. win.setSkipTaskbar(false);
  108. taskbarHidden = false;
  109. }
  110. const finalImage = await captureWithTimeout(
  111. guest,
  112. { x: 0, y: 0, width: 320, height: 200 },
  113. "hidden-born final capture",
  114. );
  115. if (finalImage.isEmpty()) {
  116. throw new Error("hidden-born final capture remained empty after bootstrap cleanup");
  117. }
  118. if (win.isVisible() || win.isFocused() || win.getOpacity() !== originalOpacity) {
  119. throw new Error(
  120. `transparent bootstrap did not restore window state: ${JSON.stringify({
  121. focused: win.isFocused(),
  122. opacity: win.getOpacity(),
  123. originalOpacity,
  124. visible: win.isVisible(),
  125. })}`,
  126. );
  127. }
  128. console.log(
  129. JSON.stringify({
  130. bootstrapSizes: bootstrapImages.map((image) => image.getSize()),
  131. finalSize: finalImage.getSize(),
  132. focused: win.isFocused(),
  133. opacity: win.getOpacity(),
  134. platform: process.platform,
  135. taskbarRestored: !taskbarHidden,
  136. visible: win.isVisible(),
  137. }),
  138. );
  139. } catch (error) {
  140. exitCode = 1;
  141. console.error(error);
  142. } finally {
  143. if (win && !win.isDestroyed()) {
  144. if (win.isVisible()) win.hide();
  145. if (originalOpacity !== undefined) win.setOpacity(originalOpacity);
  146. if (taskbarHidden) win.setSkipTaskbar(false);
  147. win.destroy();
  148. }
  149. app.exit(exitCode);
  150. }
  151. }
  152. void run();