51 lines
1.7 KiB
JavaScript
51 lines
1.7 KiB
JavaScript
// 通过 CDP 检查模拟器浏览器中页面的移动端布局
|
|
const wsUrl = process.argv[2] || "ws://127.0.0.1:9222/devtools/page/2";
|
|
|
|
const ws = new WebSocket(wsUrl);
|
|
let id = 0;
|
|
const pending = new Map();
|
|
|
|
function send(method, params = {}) {
|
|
return new Promise((resolve, reject) => {
|
|
const msgId = ++id;
|
|
pending.set(msgId, { resolve, reject });
|
|
ws.send(JSON.stringify({ id: msgId, method, params }));
|
|
});
|
|
}
|
|
|
|
ws.onmessage = (event) => {
|
|
const msg = JSON.parse(event.data);
|
|
if (msg.id && pending.has(msg.id)) {
|
|
const { resolve, reject } = pending.get(msg.id);
|
|
pending.delete(msg.id);
|
|
if (msg.error) reject(new Error(JSON.stringify(msg.error)));
|
|
else resolve(msg.result);
|
|
}
|
|
};
|
|
|
|
ws.onerror = (e) => {
|
|
console.error("WS error:", e.message || e);
|
|
process.exit(1);
|
|
};
|
|
|
|
ws.onopen = async () => {
|
|
try {
|
|
const expr = `JSON.stringify({
|
|
viewport: { w: window.innerWidth, h: window.innerHeight, dpr: window.devicePixelRatio },
|
|
doc: { scrollW: document.documentElement.scrollWidth, clientW: document.documentElement.clientWidth, scrollH: document.documentElement.scrollHeight },
|
|
body: { scrollW: document.body.scrollWidth, clientW: document.body.clientWidth },
|
|
overflowX: document.documentElement.scrollWidth > document.documentElement.clientWidth,
|
|
title: document.title,
|
|
url: location.href,
|
|
navVisible: !!document.querySelector('nav, header'),
|
|
bodyTextLen: document.body.innerText.length
|
|
})`;
|
|
const res = await send("Runtime.evaluate", { expression: expr, returnByValue: true });
|
|
console.log(res.result.value);
|
|
} catch (e) {
|
|
console.error("Error:", e.message);
|
|
} finally {
|
|
ws.close();
|
|
process.exit(0);
|
|
}
|
|
}; |