在Chrome中加载页面时,我正在使用以下代码记录已编码的响应大小:
const puppeteer = require("puppeteer");
(async function() {
const browser = await puppeteer.launch();
const page = await browser.newPage();
page._client.on("Network.loadingFinished", data => {
console.log("finished", { encodedDataLength: data.encodedDataLength });
});
// await page.setRequestInterception(true);
// page.on("request", async request => {
// request.continue();
// });
await page.goto("http://example.com");
await browser.close();
})();
这是输出:
完成了{encodeDataLength:967}
但是,如果我取消注释代码段中的四行,输出将更改为:
完成{encodingDataLength:0}
这确实是有道理的,因为被拦截的请求可能已由客户端以某种方式进行了修改,此后再也不会被压缩。
但是,有没有办法访问原始的压缩响应大小?
Chrome浏览器跟踪也不包含压缩后的大小:
“ encodedDataLength”:0, “ decodedBodyLength”:1270,
答案 0 :(得分:1)
在这种情况下,我们可以使用Content-Length
标头值。
Google的好人认为他们不会修复与encodedDataLength
密切相关的some weird bugs。
检查下面的代码和结果以查看证明。
page.on("request", async request => {
request.continue();
});
// Monitor using _client
page._client.on("Network.responseReceived", ({ response }) => {
console.log("responseReceived", [
response.headers["Content-Length"],
response.encodedDataLength
]);
});
page._client.on("Network.loadingFinished", data => {
console.log("loadingFinished", [data.encodedDataLength]);
});
// Monitor using CDP
const devToolsResponses = new Map();
const devTools = await page.target().createCDPSession();
await devTools.send("Network.enable");
devTools.on("Network.responseReceived", event => {
devToolsResponses.set(event.requestId, event.response);
});
devTools.on("Network.loadingFinished", event => {
const response = devToolsResponses.get(event.requestId);
const encodedBodyLength =
event.encodedDataLength - response.headersText.length;
console.log(`${encodedBodyLength} bytes for ${response.url}`);
});
结果无 setRequestInterception:
responseReceived [ '606', 361 ]
loadingFinished [ 967 ]
606 bytes for http://example.com/
结果,带有 setRequestInterception:
responseReceived [ '606', 0 ]
loadingFinished [ 0 ]
-361 bytes for http://example.com/
Content-Length
标题在每种意义上都更加可靠。