1 回答
TA贡献1770条经验 获得超3个赞
使用PerformanceObserver,您可以通过将条目类型指定为“资源”来获取每个请求的时间。将每个条目添加到对象window,然后使用 puppeteer 对其进行评估。
const puppeteer = require('puppeteer');
const perfObsRunner = () => {
window.resourceList = [];
new PerformanceObserver((list) => {
list.getEntries().forEach((item) => {
window.resourceList = [...window.resourceList, item.toJSON()]
})
}).observe({type: 'resource', buffered: true});
}
const getResourceTiming = async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.evaluateOnNewDocument(perfObsRunner);
await page.goto("https://pptr.dev/", { waitUntil: 'load', timeout: 30000 });
const resource = await page.evaluate(() => ({ resource: window.resourceList }))
await page.close();
await browser.close();
}
从响应中您可以获取有关请求的信息,例如:startTime、duration、responseStart、responseEnd。 示例响应:
resource = [
{
"name": "https://pptr.dev/style.css",
"entryType": "resource",
"startTime": 55.9099999954924,
"duration": 0,
"initiatorType": "link",
"nextHopProtocol": "h2",
"workerStart": 0,
"redirectStart": 0,
"redirectEnd": 0,
"fetchStart": 55.9099999954924,
"domainLookupStart": 55.9099999954924,
"domainLookupEnd": 55.9099999954924,
"connectStart": 55.9099999954924,
"connectEnd": 55.9099999954924,
"secureConnectionStart": 55.9099999954924,
"requestStart": 0,
"responseStart": 0,
"responseEnd": 55.9099999954924,
"transferSize": 0,
"encodedBodySize": 3704,
"decodedBodySize": 14326,
"serverTiming": [],
"workerTiming": []
},
{
"name": "https://pptr.dev/index.js",
"entryType": "resource",
"startTime": 56.08000000938773,
"duration": 0,
"initiatorType": "script",
"nextHopProtocol": "h2",
"workerStart": 0,
"redirectStart": 0,
"redirectEnd": 0,
"fetchStart": 56.08000000938773,
"domainLookupStart": 56.08000000938773,
"domainLookupEnd": 56.08000000938773,
"connectStart": 56.08000000938773,
"connectEnd": 56.08000000938773,
"secureConnectionStart": 56.08000000938773,
"requestStart": 0,
"responseStart": 0,
"responseEnd": 56.08000000938773,
"transferSize": 0,
"encodedBodySize": 52861,
"decodedBodySize": 149772,
"serverTiming": [],
"workerTiming": []
},
{
"name": "https://raw.githubusercontent.com/GoogleChrome/puppeteer/main/README.md",
"entryType": "resource",
"startTime": 98.98000000976026,
"duration": 1.6949999844655395,
"initiatorType": "fetch",
"nextHopProtocol": "h2",
"workerStart": 0,
"redirectStart": 0,
"redirectEnd": 0,
"fetchStart": 98.98000000976026,
"domainLookupStart": 0,
"domainLookupEnd": 0,
"connectStart": 0,
"connectEnd": 0,
"secureConnectionStart": 0,
"requestStart": 0,
"responseStart": 0,
"responseEnd": 100.6749999942258,
"transferSize": 0,
"encodedBodySize": 0,
"decodedBodySize": 0,
"serverTiming": [],
"workerTiming": []
},
]
添加回答
举报