如何通过脚本读取开发者工具中的数据传输信息?
可以读取并监控对应请求的下载状态数值
你可以通过前端脚本实现类似开发者工具Network标签的下载状态监控,针对你的Unity WebGL场景,推荐两种可行方案:
方案一:拦截XMLHttpRequest/fetch请求,监听实时进度
Unity WebGL导出的应用通常会通过XMLHttpRequest或fetch发起资源请求,你可以重写这两个API,针对目标URL监听下载进度:
拦截XMLHttpRequest(适用于传统AJAX请求)
// 保存原始open方法 const originalXHR = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(method, url) { // 匹配你要监控的目标URL(可根据实际情况调整匹配规则) if (url === '你的目标资源URL') { // 监听progress事件获取实时进度 this.addEventListener('progress', (event) => { if (event.lengthComputable) { const loadedBytes = event.loaded; const totalBytes = event.total; const progressPercent = (loadedBytes / totalBytes) * 100; // 这里替换成你的自定义进度条更新逻辑 console.log(`当前下载进度:${progressPercent.toFixed(2)}%`); } }); } // 调用原始方法 originalXHR.apply(this, arguments); };
拦截fetch请求(适用于现代fetch API请求)
fetch本身没有内置的progress事件,需要通过读取响应流来计算进度:
const originalFetch = window.fetch; window.fetch = async function(resource, options) { const targetUrl = typeof resource === 'string' ? resource : resource.url; // 匹配目标URL if (targetUrl === '你的目标资源URL') { const response = await originalFetch(resource, options); // 克隆响应(响应流只能被读取一次) const clonedResponse = response.clone(); const totalBytes = parseInt(clonedResponse.headers.get('Content-Length')); let loadedBytes = 0; // 读取响应流计算进度 const reader = clonedResponse.body.getReader(); while (true) { const { done, value } = await reader.read(); if (done) break; loadedBytes += value.length; const progressPercent = (loadedBytes / totalBytes) * 100; // 更新自定义进度条 console.log(`当前下载进度:${progressPercent.toFixed(2)}%`); } return response; } return originalFetch(resource, options); };
方案二:使用PerformanceObserver获取资源加载数据
如果只需要获取请求完成后的加载数据(而非实时进度),可以通过PerformanceObserver监听性能条目:
const observer = new PerformanceObserver((list) => { for (const entry of list.getEntries()) { // 匹配目标URL if (entry.name === '你的目标资源URL') { console.log(`资源总大小:${entry.transferSize}字节`); console.log(`已加载大小:${entry.encodedBodySize}字节`); } } }); // 监听资源加载条目 observer.observe({ entryTypes: ['resource'] });
注意事项
- 上述代码需要在Unity WebGL应用加载前注入(比如放在页面的
<head>标签中),确保能覆盖Unity的请求方法。 - 如果Unity使用WebAssembly直接发起网络请求(绕过浏览器API),则需要通过Chrome DevTools Protocol(CDP)来监控,但这种方式通常需要浏览器扩展或调试工具支持,不适合前端页面脚本直接实现。
内容的提问来源于stack exchange,提问作者Tiranyk
相关产品推荐
相关产品推荐

