227 lines
8.3 KiB
JavaScript
227 lines
8.3 KiB
JavaScript
const fs = require('fs')
|
|
const path = require('path')
|
|
|
|
const [url, selector, output, width = '360', height = '800', action] = process.argv.slice(2)
|
|
const renderSettleMilliseconds = 900
|
|
const chromeDebuggingPort = process.env.CHROME_DEBUGGING_PORT || '9222'
|
|
|
|
if (!url || !selector || !output) {
|
|
throw new Error('Usage: node scripts/capture-chrome-page.js <url> <selector> <output> [width] [height] [password-tab|sms-tab|g06-results|g06-empty|g06-invite|fresh-navigation]')
|
|
}
|
|
|
|
const sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds))
|
|
|
|
const connect = async () => {
|
|
const pages = await (await fetch(`http://127.0.0.1:${chromeDebuggingPort}/json/list`)).json()
|
|
const page = pages.find((item) => item.type === 'page' && item.url.startsWith('http://localhost:5173'))
|
|
if (!page) throw new Error('Chrome debugging has no localhost:5173 page')
|
|
|
|
const socket = new WebSocket(page.webSocketDebuggerUrl)
|
|
await new Promise((resolve, reject) => {
|
|
socket.addEventListener('open', resolve, { once: true })
|
|
socket.addEventListener('error', reject, { once: true })
|
|
})
|
|
|
|
let id = 0
|
|
const pending = new Map()
|
|
socket.addEventListener('message', (event) => {
|
|
const message = JSON.parse(event.data)
|
|
const request = pending.get(message.id)
|
|
if (!request) return
|
|
pending.delete(message.id)
|
|
if (message.error) request.reject(new Error(message.error.message))
|
|
else request.resolve(message.result)
|
|
})
|
|
|
|
const send = (method, params = {}) => new Promise((resolve, reject) => {
|
|
id += 1
|
|
pending.set(id, { resolve, reject })
|
|
socket.send(JSON.stringify({ id, method, params }))
|
|
})
|
|
|
|
return { socket, send }
|
|
}
|
|
|
|
const waitForLoadedImages = async (send) => {
|
|
for (let attempt = 0; attempt < 30; attempt += 1) {
|
|
const result = await send('Runtime.evaluate', {
|
|
expression: 'Array.from(document.images).every((image) => image.complete && image.naturalWidth > 0)',
|
|
returnByValue: true
|
|
})
|
|
if (result.result?.value) return
|
|
if (attempt === 29) throw new Error('Page images did not finish loading before screenshot')
|
|
await sleep(100)
|
|
}
|
|
}
|
|
|
|
const prepareA01LoginState = async (send, action) => {
|
|
if (action !== 'password-tab' && action !== 'sms-tab') return
|
|
const tabIndex = action === 'password-tab' ? 0 : 1
|
|
|
|
for (let attempt = 0; attempt < 30; attempt += 1) {
|
|
const prepared = await send('Runtime.evaluate', {
|
|
expression: `(() => {
|
|
const tabs = document.querySelectorAll('.login-tab')
|
|
if (tabs.length < 2) return false
|
|
tabs[${tabIndex}].click()
|
|
return true
|
|
})()`,
|
|
returnByValue: true
|
|
})
|
|
if (prepared.result?.value) break
|
|
if (attempt === 29) throw new Error(`A01 login tabs did not render for ${action}`)
|
|
await sleep(100)
|
|
}
|
|
|
|
for (let attempt = 0; attempt < 30; attempt += 1) {
|
|
const active = await send('Runtime.evaluate', {
|
|
expression: `document.querySelectorAll('.login-tab')[${tabIndex}]?.classList.contains('active') === true`,
|
|
returnByValue: true
|
|
})
|
|
if (active.result?.value) return
|
|
if (attempt === 29) throw new Error(`A01 did not enter the requested ${action} state`)
|
|
await sleep(100)
|
|
}
|
|
}
|
|
|
|
const waitForRequestedUrl = async (send, url) => {
|
|
for (let attempt = 0; attempt < 30; attempt += 1) {
|
|
const result = await send('Runtime.evaluate', {
|
|
expression: `location.href === ${JSON.stringify(url)}`,
|
|
returnByValue: true
|
|
})
|
|
if (result.result?.value) return
|
|
if (attempt === 29) throw new Error(`Browser did not navigate to the requested URL: ${url}`)
|
|
await sleep(100)
|
|
}
|
|
}
|
|
|
|
const waitForFreshDocument = async (send, documentTimeOrigin) => {
|
|
for (let attempt = 0; attempt < 30; attempt += 1) {
|
|
const result = await send('Runtime.evaluate', {
|
|
expression: 'performance.timeOrigin',
|
|
returnByValue: true
|
|
})
|
|
if (result.result?.value !== documentTimeOrigin) return
|
|
if (attempt === 29) throw new Error('Page did not reload into a fresh document before screenshot')
|
|
await sleep(100)
|
|
}
|
|
}
|
|
|
|
const prepareG06State = async (send, action) => {
|
|
if (action !== 'g06-results' && action !== 'g06-empty' && action !== 'g06-invite') return
|
|
|
|
if (action === 'g06-invite') {
|
|
const switched = await send('Runtime.evaluate', {
|
|
expression: `(() => {
|
|
const tab = document.querySelectorAll('.mode-tab')[1]
|
|
if (!tab) return false
|
|
tab.click()
|
|
return true
|
|
})()`,
|
|
returnByValue: true
|
|
})
|
|
if (!switched.result?.value) throw new Error('Could not switch G06 to invite mode')
|
|
await sleep(100)
|
|
const prepared = await send('Runtime.evaluate', {
|
|
expression: `(() => {
|
|
const input = document.querySelector('.invite-input input')
|
|
const button = document.querySelector('.invite-controls .search-action')
|
|
if (!input || !button) return false
|
|
input.value = 'JP2026'
|
|
input.dispatchEvent(new Event('input', { bubbles: true }))
|
|
return true
|
|
})()`,
|
|
returnByValue: true
|
|
})
|
|
if (!prepared.result?.value) throw new Error('Could not prepare G06 invite code')
|
|
await sleep(100)
|
|
await send('Runtime.evaluate', { expression: "document.querySelector('.invite-controls .search-action').click()" })
|
|
} else {
|
|
|
|
const keyword = action === 'g06-results' ? '汤' : '不存在的家谱'
|
|
const prepared = await send('Runtime.evaluate', {
|
|
expression: `(() => {
|
|
const input = document.querySelector('.search-input input')
|
|
if (!input) return false
|
|
input.value = ${JSON.stringify(keyword)}
|
|
input.dispatchEvent(new Event('input', { bubbles: true }))
|
|
return true
|
|
})()`,
|
|
returnByValue: true
|
|
})
|
|
if (!prepared.result?.value) throw new Error(`Could not prepare ${action}`)
|
|
await sleep(100)
|
|
await send('Runtime.evaluate', { expression: "document.querySelector('.search-action').click()" })
|
|
}
|
|
|
|
const stateSelector = action === 'g06-results' ? '.search-results .genealogy-card' : action === 'g06-empty' ? '.search-empty' : '.invite-result .genealogy-card'
|
|
for (let attempt = 0; attempt < 30; attempt += 1) {
|
|
const result = await send('Runtime.evaluate', {
|
|
expression: `Boolean(document.querySelector(${JSON.stringify(stateSelector)}))`,
|
|
returnByValue: true
|
|
})
|
|
if (result.result?.value) return
|
|
if (attempt === 29) throw new Error(`Expected G06 state did not render: ${action}`)
|
|
await sleep(100)
|
|
}
|
|
}
|
|
|
|
const capture = async () => {
|
|
const { socket, send } = await connect()
|
|
const viewportWidth = Number(width)
|
|
const viewportHeight = Number(height)
|
|
|
|
try {
|
|
await send('Page.enable')
|
|
await send('Runtime.enable')
|
|
await send('Emulation.setDeviceMetricsOverride', {
|
|
width: viewportWidth,
|
|
height: viewportHeight,
|
|
deviceScaleFactor: 1,
|
|
mobile: true,
|
|
screenWidth: viewportWidth,
|
|
screenHeight: viewportHeight
|
|
})
|
|
const timeOriginResult = await send('Runtime.evaluate', {
|
|
expression: 'performance.timeOrigin',
|
|
returnByValue: true
|
|
})
|
|
const documentTimeOrigin = timeOriginResult.result?.value
|
|
await send('Page.navigate', { url })
|
|
await waitForRequestedUrl(send, url)
|
|
if (action !== 'fresh-navigation') {
|
|
await send('Page.reload')
|
|
await waitForFreshDocument(send, documentTimeOrigin)
|
|
}
|
|
|
|
for (let attempt = 0; attempt < 30; attempt += 1) {
|
|
const result = await send('Runtime.evaluate', {
|
|
expression: `Boolean(document.querySelector(${JSON.stringify(selector)}))`,
|
|
returnByValue: true
|
|
})
|
|
if (result.result?.value) break
|
|
if (attempt === 29) throw new Error(`Expected page selector did not render: ${selector}`)
|
|
await sleep(100)
|
|
}
|
|
|
|
await prepareA01LoginState(send, action)
|
|
await prepareG06State(send, action)
|
|
|
|
await waitForLoadedImages(send)
|
|
await sleep(renderSettleMilliseconds)
|
|
const screenshot = await send('Page.captureScreenshot', { format: 'png', fromSurface: true, captureBeyondViewport: false })
|
|
fs.mkdirSync(path.dirname(output), { recursive: true })
|
|
fs.writeFileSync(output, Buffer.from(screenshot.data, 'base64'))
|
|
process.stdout.write(`CAPTURED ${output}\n`)
|
|
} finally {
|
|
try { await send('Emulation.clearDeviceMetricsOverride') } catch (_) {}
|
|
socket.close()
|
|
}
|
|
}
|
|
|
|
capture().catch((error) => {
|
|
process.stderr.write(`${error.stack || error.message}\n`)
|
|
process.exit(1)
|
|
})
|