Files
mcn-short-video/project/短视频脚本创作/V1.0/mcn-workshop/cdp-measure-cols.mjs
T

58 lines
2.7 KiB
JavaScript
Raw Normal View History

/* cdp-measure-cols.mjs — 测量账号详情视频列表各列实际宽度(09-01) */
const CDP = 'http://127.0.0.1:9223';
async function getWs(targetId) {
const tabs = await (await fetch(CDP + '/json')).json();
const t = tabs.find((x) => x.id === targetId);
if (!t) throw new Error('target not found: ' + targetId);
return t.webSocketDebuggerUrl;
}
function cdp(ws, method, params = {}) {
return new Promise((resolve, reject) => {
const id = ++cdp._id;
const w = new WebSocket(ws);
const timer = setTimeout(() => { try { w.close(); } catch (e) {} reject(new Error('timeout: ' + method)); }, 30000);
w.onopen = () => w.send(JSON.stringify({ id, method, params }));
w.onmessage = (ev) => {
const m = JSON.parse(ev.data);
if (m.id !== id) return;
clearTimeout(timer);
try { w.close(); } catch (e) {}
m.error ? reject(new Error(method + ': ' + JSON.stringify(m.error))) : resolve(m.result);
};
w.onerror = () => { clearTimeout(timer); reject(new Error('ws error: ' + method)); };
});
}
cdp._id = 0;
async function evalJs(ws, expr) {
const r = await cdp(ws, 'Runtime.evaluate', { expression: expr, awaitPromise: true, returnByValue: true });
if (r.exceptionDetails) throw new Error('eval err: ' + JSON.stringify(r.exceptionDetails).slice(0, 300));
return r.result && r.result.value;
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function main() {
const tabs = await (await fetch(CDP + '/json')).json();
const tab = tabs.find((x) => x.url.includes('localhost:8900')) || tabs.find((x) => x.type === 'page');
if (!tab) throw new Error('no 8900 tab found');
const ws = await getWs(tab.id);
await cdp(ws, 'Page.enable');
await cdp(ws, 'Runtime.enable');
await cdp(ws, 'Page.navigate', { url: 'http://localhost:8900/?v=measure' + '#/account/3' });
await sleep(2500);
const r = await evalJs(ws, `(() => {
const ths = [...document.querySelectorAll('.video-list-title ~ .table-wrap thead th, .table thead th')];
const first = document.querySelector('.table tbody tr');
const tds = first ? [...first.children] : [];
const w = (el) => el ? Math.round(el.getBoundingClientRect().width) : -1;
return {
ths: ths.map((t) => ({ text: t.textContent.trim(), w: w(t), cls: t.className })),
tds: tds.map((t) => ({ text: (t.textContent || '').trim().slice(0, 12), w: w(t), cls: t.className })),
tableW: w(document.querySelector('.table-wrap .table')),
wrapW: w(document.querySelector('.table-wrap')),
err: document.querySelector('.page') ? document.querySelector('.page').textContent.slice(0, 100) : null
};
})()`);
console.log(JSON.stringify(r, null, 2));
process.exit(0);
}
main().catch((e) => { console.error('ERROR:', e.message); process.exit(1); });