scripts/cdp_client.mjs
6.5 KB| 1 | // Generic CDP client for driving an already-running browser over the DevTools protocol. |
| 2 | // Requires Node 18+ with global fetch + WebSocket (Node 22 recommended; no npm deps). |
| 3 | // |
| 4 | // Usage: |
| 5 | // node cdp_client.mjs <command> [args...] |
| 6 | // |
| 7 | // Commands: |
| 8 | // nav <url> navigate the first page target |
| 9 | // dom print document.body.innerText (up to 40000 chars) |
| 10 | // eval <js-expression> evaluate JS in page and print result |
| 11 | // url print current URL |
| 12 | // title print document.title |
| 13 | // shot <path> [quality] capture viewport screenshot to <path> (default quality 70) |
| 14 | // clicktext <text> click first visible button/a whose text equals/contains <text> |
| 15 | // clickxy <x> <y> dispatch a real mouse click at viewport CSS coordinates |
| 16 | // login print login-state probe as JSON |
| 17 | // cookies print Epic-related cookies visible to CDP as JSON |
| 18 | // pause close the websocket (browser stays open) |
| 19 | // |
| 20 | // Environment: |
| 21 | // CDP_PORT debugger port (default 9222) |
| 22 | // CDP_URL full websocket target URL (optional; overrides target discovery) |
| 23 | |
| 24 | const PORT = Number(process.env.CDP_PORT || 9222); |
| 25 | const CDP_URL = process.env.CDP_URL || ''; |
| 26 | let ws; |
| 27 | let msgId = 0; |
| 28 | const pending = new Map(); |
| 29 | |
| 30 | async function discoverTarget() { |
| 31 | if (CDP_URL) return CDP_URL; |
| 32 | const targets = await (await fetch(`http://127.0.0.1:${PORT}/json`)).json(); |
| 33 | let page = targets.find(t => t.type === 'page' && t.url && !t.url.startsWith('devtools://')); |
| 34 | if (!page) { |
| 35 | await fetch(`http://127.0.0.1:${PORT}/json/new?about:blank`, { method: 'PUT' }); |
| 36 | const t2 = await (await fetch(`http://127.0.0.1:${PORT}/json`)).json(); |
| 37 | page = t2.find(t => t.type === 'page'); |
| 38 | } |
| 39 | if (!page) throw new Error('No page target available on CDP port ' + PORT); |
| 40 | return page.webSocketDebuggerUrl; |
| 41 | } |
| 42 | |
| 43 | async function connect() { |
| 44 | const url = await discoverTarget(); |
| 45 | ws = new WebSocket(url); |
| 46 | await new Promise((res, rej) => { ws.onopen = res; ws.onerror = rej; }); |
| 47 | ws.onmessage = (ev) => { |
| 48 | const m = JSON.parse(ev.data); |
| 49 | if (m.id && pending.has(m.id)) { |
| 50 | const { resolve, reject } = pending.get(m.id); |
| 51 | pending.delete(m.id); |
| 52 | if (m.error) reject(new Error(JSON.stringify(m.error))); |
| 53 | else resolve(m.result); |
| 54 | } |
| 55 | }; |
| 56 | } |
| 57 | |
| 58 | function send(method, params = {}) { |
| 59 | const id = ++msgId; |
| 60 | return new Promise((resolve, reject) => { |
| 61 | pending.set(id, { resolve, reject }); |
| 62 | ws.send(JSON.stringify({ id, method, params })); |
| 63 | }); |
| 64 | } |
| 65 | |
| 66 | async function evaluate(expression, awaitPromise = true) { |
| 67 | const r = await send('Runtime.evaluate', { |
| 68 | expression, |
| 69 | returnByValue: true, |
| 70 | awaitPromise, |
| 71 | userGesture: true, |
| 72 | }); |
| 73 | if (r.exceptionDetails) { |
| 74 | throw new Error('EVAL EXCEPTION: ' + JSON.stringify( |
| 75 | r.exceptionDetails.exception?.description || r.exceptionDetails.text)); |
| 76 | } |
| 77 | return r.result.value; |
| 78 | } |
| 79 | |
| 80 | const sleep = (ms) => new Promise(r => setTimeout(r, ms)); |
| 81 | |
| 82 | async function main() { |
| 83 | await connect(); |
| 84 | const [cmd, ...rest] = process.argv.slice(2); |
| 85 | const arg = rest.join(' '); |
| 86 | |
| 87 | if (cmd === 'nav') { |
| 88 | await send('Page.enable'); |
| 89 | await send('Page.navigate', { url: arg }); |
| 90 | console.log('NAV_OK ' + arg); |
| 91 | } else if (cmd === 'dom') { |
| 92 | const v = await evaluate(`(document.body ? document.body.innerText : '').slice(0,40000)`); |
| 93 | console.log(v); |
| 94 | } else if (cmd === 'eval') { |
| 95 | const v = await evaluate(arg); |
| 96 | console.log(typeof v === 'string' ? v : JSON.stringify(v, null, 2)); |
| 97 | } else if (cmd === 'url') { |
| 98 | console.log(await evaluate('location.href')); |
| 99 | } else if (cmd === 'title') { |
| 100 | console.log(await evaluate('document.title')); |
| 101 | } else if (cmd === 'shot') { |
| 102 | const [path, q] = rest; |
| 103 | const { data } = await send('Page.captureScreenshot', { |
| 104 | format: 'jpeg', |
| 105 | quality: Number(q || 70), |
| 106 | }); |
| 107 | const fs = await import('node:fs'); |
| 108 | fs.writeFileSync(path, Buffer.from(data, 'base64')); |
| 109 | console.log('SHOT_OK ' + path); |
| 110 | } else if (cmd === 'clicktext') { |
| 111 | const js = `(() => { |
| 112 | const target = ${JSON.stringify(arg)}; |
| 113 | const els = [...document.querySelectorAll('button,a,[role="button"]')]; |
| 114 | const el = els.find(e => { |
| 115 | const t = (e.innerText || e.textContent || '').trim(); |
| 116 | const r = e.getBoundingClientRect(); |
| 117 | return r.width > 0 && r.height > 0 && |
| 118 | (t === target || (target.length > 3 && t.includes(target))); |
| 119 | }); |
| 120 | if (!el) return 'NO_MATCH'; |
| 121 | el.scrollIntoView({block:'center'}); |
| 122 | el.click(); |
| 123 | return 'CLICKED:' + (el.innerText || el.textContent || '').trim(); |
| 124 | })()`; |
| 125 | console.log(await evaluate(js)); |
| 126 | } else if (cmd === 'clickxy') { |
| 127 | const x = Number(rest[0]); |
| 128 | const y = Number(rest[1]); |
| 129 | await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y }); |
| 130 | await send('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 }); |
| 131 | await send('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 }); |
| 132 | console.log(`CLICKED_XY ${x},${y}`); |
| 133 | } else if (cmd === 'login') { |
| 134 | const js = `(() => { |
| 135 | const am = document.querySelector('[aria-label="Account menu"]'); |
| 136 | const loginLink = [...document.querySelectorAll('a')] |
| 137 | .find(a => /^\\s*(登录|sign in|log in)\\s*$/i.test((a.innerText||'').trim())); |
| 138 | const headerBtns = [...document.querySelectorAll('button,a')] |
| 139 | .filter(e => /领取|拥有|已在库中|获取|添加到库/.test((e.innerText||'').trim())) |
| 140 | .map(e => (e.innerText||'').trim()).slice(0,10); |
| 141 | return JSON.stringify({ |
| 142 | accountMenuTitle: am ? (am.getAttribute('title') || '') : null, |
| 143 | hasLoginLink: !!loginLink, |
| 144 | loggedIn: !!(am && am.getAttribute('title')) && !loginLink, |
| 145 | actionButtons: [...new Set(headerBtns)], |
| 146 | cookieLen: document.cookie.length |
| 147 | }); |
| 148 | })()`; |
| 149 | console.log(await evaluate(js)); |
| 150 | } else if (cmd === 'cookies') { |
| 151 | await send('Network.enable'); |
| 152 | const r = await send('Network.getAllCookies'); |
| 153 | const epic = (r.cookies || []).filter(c => /epicgames/.test(c.domain)); |
| 154 | console.log(JSON.stringify(epic.map(c => ({ |
| 155 | domain: c.domain, |
| 156 | name: c.name, |
| 157 | httpOnly: c.httpOnly, |
| 158 | expires: c.expires > 0 ? new Date(c.expires * 1000).toISOString() : 'session' |
| 159 | })), null, 2)); |
| 160 | } else if (cmd === 'pause') { |
| 161 | console.log('PAUSE_OK'); |
| 162 | } else { |
| 163 | console.log('unknown command: ' + cmd); |
| 164 | console.log('use: nav|dom|eval|url|title|shot|clicktext|clickxy|login|cookies|pause'); |
| 165 | } |
| 166 | ws.close(); |
| 167 | } |
| 168 | |
| 169 | main().catch(e => { console.error('ERR ' + e.message); process.exit(1); }); |
文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。

