36 lines
1.3 KiB
JavaScript
36 lines
1.3 KiB
JavaScript
// Dev helper: evaluates JavaScript in the running WebView2 page via the DevTools protocol.
|
|
// Usage: node scripts/cdp.mjs "<expression>" [--shot out.png]
|
|
import { writeFileSync } from "node:fs";
|
|
|
|
const args = process.argv.slice(2);
|
|
const shotIdx = args.indexOf("--shot");
|
|
const shot = shotIdx >= 0 ? args.splice(shotIdx, 2)[1] : null;
|
|
const expression = args[0] ?? "document.title";
|
|
|
|
const targets = await (await fetch("http://127.0.0.1:9222/json")).json();
|
|
const page = targets.find((t) => t.type === "page");
|
|
if (!page) throw new Error("Keine Seite gefunden");
|
|
|
|
const ws = new WebSocket(page.webSocketDebuggerUrl);
|
|
let id = 0;
|
|
const pending = new Map();
|
|
ws.onmessage = (event) => {
|
|
const msg = JSON.parse(event.data);
|
|
if (msg.id && pending.has(msg.id)) pending.get(msg.id)(msg);
|
|
};
|
|
const send = (method, params = {}) =>
|
|
new Promise((resolve) => {
|
|
const myId = ++id;
|
|
pending.set(myId, resolve);
|
|
ws.send(JSON.stringify({ id: myId, method, params }));
|
|
});
|
|
await new Promise((resolve) => (ws.onopen = resolve));
|
|
|
|
const res = await send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true });
|
|
console.log(JSON.stringify(res.result?.result?.value ?? res.result, null, 2));
|
|
if (shot) {
|
|
const img = await send("Page.captureScreenshot", { format: "png" });
|
|
writeFileSync(shot, Buffer.from(img.result.data, "base64"));
|
|
}
|
|
ws.close();
|