Files
ycode/scripts/click-shot.mjs
T

81 lines
2.5 KiB
JavaScript

/**
* 交互验收:点击指定选择器后截图。
* 用法:node scripts/click-shot.mjs <port> <selector> <outPng>
*/
import { writeFile } from 'node:fs/promises'
const port = Number(process.argv[2] ?? 9335)
const selector = process.argv[3] ?? 'button'
const outPng = process.argv[4] ?? 'shot.png'
async function main() {
const list = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json()
const page = list.filter((t) => t.type === 'page')[0]
if (!page) throw new Error('未找到页面')
const ws = new WebSocket(page.webSocketDebuggerUrl)
await new Promise((r, j) => {
const t = setTimeout(() => j(new Error('连接超时')), 8000)
ws.addEventListener('open', () => {
clearTimeout(t)
r()
})
ws.addEventListener('error', () => {
clearTimeout(t)
j(new Error('连接失败'))
})
})
const send = (method, params = {}) =>
new Promise((res, rej) => {
const id = Math.floor(Math.random() * 1e9)
const timer = setTimeout(() => rej(new Error(`超时 ${method}`)), 15000)
const h = (ev) => {
const m = JSON.parse(ev.data)
if (m.id === id) {
clearTimeout(timer)
ws.removeEventListener('message', h)
res(m.result)
}
}
ws.addEventListener('message', h)
ws.send(JSON.stringify({ id, method, params }))
})
// 用 title 属性选中目标(比 :nth-child 稳)
const clickExpr = `(() => {
const el = document.querySelector(${JSON.stringify(selector)});
if (!el) return 'NOT_FOUND';
el.click();
return 'CLICKED: ' + (el.getAttribute('title') || el.className || '');
})()`
const r = await send('Runtime.evaluate', { expression: clickExpr, returnByValue: true })
console.log('点击结果:', r.result.value)
await new Promise((res) => setTimeout(res, 700))
const probe = await send('Runtime.evaluate', {
expression: `JSON.stringify({
notif: !!document.querySelector('.notif-panel'),
notifItems: document.querySelectorAll('.notif-item').length,
settings: !!document.querySelector('.dialog--settings'),
settingsNav: document.querySelectorAll('.settings__nav-item').length
})`,
returnByValue: true
})
console.log('面板状态:', probe.result.value)
const shot = await send('Page.captureScreenshot', { format: 'png' })
if (shot?.data) {
await writeFile(outPng, Buffer.from(shot.data, 'base64'))
console.log('截图:', outPng)
}
ws.close()
}
main().catch((e) => {
console.error('失败:', e.message)
process.exit(1)
})