完成40%

This commit is contained in:
rain
2026-07-14 17:36:39 +08:00
parent 1015e60ff7
commit 8c98936da5
151 changed files with 5132 additions and 351 deletions
+47 -1
View File
@@ -2,6 +2,7 @@ const fs = require('fs')
const path = require('path')
const [url, selector, output, width = '360', height = '800', action] = process.argv.slice(2)
const renderSettleMilliseconds = 900
if (!url || !selector || !output) {
throw new Error('Usage: node scripts/capture-chrome-page.js <url> <selector> <output> [width] [height] [sms-tab]')
@@ -40,6 +41,42 @@ const connect = async () => {
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 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 capture = async () => {
const { socket, send } = await connect()
const viewportWidth = Number(width)
@@ -56,7 +93,15 @@ const capture = async () => {
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)
await send('Page.reload')
await waitForFreshDocument(send, documentTimeOrigin)
for (let attempt = 0; attempt < 30; attempt += 1) {
const result = await send('Runtime.evaluate', {
@@ -74,7 +119,8 @@ const capture = async () => {
})
}
await sleep(300)
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'))