Files

56 lines
2.9 KiB
JavaScript

import { spawn } from 'node:child_process';
import { writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { resolve } from 'node:path';
const CHROME = resolve(
homedir(),
'Library/Caches/ms-playwright/chromium_headless_shell-1208/chrome-headless-shell-mac-arm64/chrome-headless-shell',
);
const PORT = 9377;
const BASE = process.argv[2] || 'http://localhost:5173';
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const chrome = spawn(CHROME, [
`--remote-debugging-port=${PORT}`, '--headless', '--disable-gpu', '--no-sandbox',
'--enable-unsafe-swiftshader', '--use-gl=angle', '--use-angle=swiftshader',
'--window-size=1440,940', '--hide-scrollbars', '--force-device-scale-factor=2', 'about:blank',
]);
chrome.stderr.on('data', () => {});
let ws, msgId = 0; const pending = new Map();
const send = (method, params = {}) => { const id = ++msgId; ws.send(JSON.stringify({ id, method, params })); return new Promise((res) => pending.set(id, res)); };
const shot = async (name) => { const s = await send('Page.captureScreenshot', { format: 'png' }); writeFileSync(`scripts/out/${name}.png`, Buffer.from(s.data, 'base64')); console.log('wrote ' + name); };
const move = (x, y) => send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y, buttons: 0 });
async function main() {
for (let i = 0; i < 40; i++) { try { if ((await (await fetch(`http://localhost:${PORT}/json/version`)).json()).webSocketDebuggerUrl) break; } catch {} await sleep(250); }
const tab = await (await fetch(`http://localhost:${PORT}/json/new?about:blank`, { method: 'PUT' })).json();
ws = new WebSocket(tab.webSocketDebuggerUrl);
await new Promise((res, rej) => { ws.onopen = res; ws.onerror = rej; });
ws.onmessage = (e) => { const m = JSON.parse(e.data); if (m.id && pending.has(m.id)) { pending.get(m.id)(m.result); pending.delete(m.id); } };
await send('Page.enable');
await send('Runtime.enable');
await send('Page.navigate', { url: BASE + '/' });
await sleep(3500);
await shot('home-full');
// hover 第一张卡片
const rect = (await send('Runtime.evaluate', {
expression: `(() => { const el=document.querySelectorAll('main, .grid > div, [class*=group]')[0]; const c=[...document.querySelectorAll('div')].find(d=>d.className.includes('group')&&d.className.includes('glass-surface')); const r=(c||document.body).getBoundingClientRect(); return JSON.stringify({x:r.x+r.width/2,y:r.y+r.height/2}); })()`,
returnByValue: true,
})).result.value;
const { x, y } = JSON.parse(rect);
await move(x, y); await sleep(700); await move(x, y + 1); await sleep(900);
await shot('home-hover');
// 打开登录弹窗
await send('Runtime.evaluate', {
expression: `[...document.querySelectorAll('button')].find(b=>/登录/.test(b.textContent))?.click()`,
});
await sleep(700);
await shot('home-login');
chrome.kill(); process.exit(0);
}
main().catch((e) => { console.error(e); chrome.kill(); process.exit(1); });