browser.mjs (2672B)
1 // Essai dans un vrai Chromium headless (protocole DevTools, sans dépendance) : 2 // ouvre l'URL, attend `secondes`, affiche la ligne de statut et les erreurs console, 3 // puis enregistre une capture d'écran. 4 // node test/browser.mjs [url] [secondes] [capture.png] [js à évaluer après l'attente] 5 import { spawn } from 'node:child_process'; 6 import { writeFileSync } from 'node:fs'; 7 8 const url = process.argv[2] ?? 'http://localhost:8081/'; 9 const secs = Number(process.argv[3] ?? 8); 10 const shot = process.argv[4] ?? '/tmp/zx81.png'; 11 const extra = process.argv[5]; 12 const port = 9333; 13 14 const chrome = spawn(process.env.CHROME ?? 'chromium', [ 15 '--headless=new', '--no-sandbox', '--disable-gpu', '--hide-scrollbars', 16 `--remote-debugging-port=${port}`, '--window-size=1000,1500', 'about:blank', 17 ], { stdio: 'ignore' }); 18 19 const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); 20 let target; 21 for (let i = 0; i < 50 && !target; i++) { 22 await sleep(200); 23 try { 24 const r = await fetch(`http://127.0.0.1:${port}/json/new?about:blank`, { method: 'PUT' }); 25 target = await r.json(); 26 } catch { /* pas encore prêt */ } 27 } 28 if (!target) { chrome.kill(); throw new Error('Chromium ne répond pas'); } 29 30 const ws = new WebSocket(target.webSocketDebuggerUrl); 31 await new Promise((r) => ws.addEventListener('open', r)); 32 let id = 0; 33 const pending = new Map(); 34 const logs = []; 35 ws.addEventListener('message', (ev) => { 36 const m = JSON.parse(ev.data); 37 if (m.id && pending.has(m.id)) { pending.get(m.id)(m.result ?? m.error); pending.delete(m.id); } 38 else if (m.method === 'Runtime.consoleAPICalled') logs.push(`[${m.params.type}] ${m.params.args.map((a) => a.value ?? a.description).join(' ')}`); 39 else if (m.method === 'Runtime.exceptionThrown') logs.push(`[exception] ${m.params.exceptionDetails.exception?.description ?? m.params.exceptionDetails.text}`); 40 }); 41 const send = (method, params = {}) => new Promise((r) => { const i = ++id; pending.set(i, r); ws.send(JSON.stringify({ id: i, method, params })); }); 42 const evaluate = async (expression) => (await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true })).result?.value; 43 44 await send('Runtime.enable'); 45 await send('Page.enable'); 46 await send('Page.navigate', { url }); 47 await sleep(secs * 1000); 48 console.log('Statut :', await evaluate("document.getElementById('status')?.textContent")); 49 if (extra) console.log('Évaluation :', JSON.stringify(await evaluate(extra))); 50 for (const l of logs) console.log(l); 51 const png = (await send('Page.captureScreenshot', { format: 'png' })).data; 52 writeFileSync(shot, Buffer.from(png, 'base64')); 53 console.log('Capture :', shot); 54 ws.close(); 55 chrome.kill();