我尝试使用这个 API
https://developer.chrome.com/extensions/webRequest
并总结了Content-Length字段,但是好像一直都缺失。有什么可行的方法吗?
chrome.webRequest.onCompleted.addListener(function(data) {
console.log('Got request!', data);
var size = 0;
for (i = 0; i < data.responseHeaders.length; i++) {
var header = data.responseHeaders[i];
if (header.name === 'Content-Length') {
size += parseInt(data.responseHeaders[i].value);
break;
}
}
if (size > 0) {
chrome.runtime.sendMessage({
msg: 'traffic',
amount: size
}, function(resp) {})
}
}, {
urls: ["<all_urls>"]
}, ["responseHeaders"]);
结果是始终缺少 Content-Length header 。
谢谢!
最佳答案
问得好,但是 webRequest
API 肯定不提供这种信息。
事实上,大多数时候服务器只是将内容推出而不事先告知它有多大,唯一可用的信息是在 onCompleted
事件中。
快速浏览the documentation没有显示此类信息。
一般来说,webRequest
显示了比网络堆栈实际执行的操作(消费)更抽象的版本。所以它不适合这份工作。
为了进一步说明这一点,这里引用了部分相关的文档:
Note that the web request API presents an abstraction of the network stack to the extension. Internally, one URL request can be split into several HTTP requests (for example to fetch individual byte ranges from a large file) or can be handled by the network stack without communicating with the network. For this reason, the API does not provide the final HTTP headers that are sent to the network. For example, all headers that are related to caching are invisible to the extension.
The following headers are currently not provided to the
onBeforeSendHeaders
event. This list is not guaranteed to be complete nor stable.
- ...
- Content-Length
- ...
我认为对此没有任何合理的方法。 chrome://net-internals/#bandwidth
显示了数据,但它没有通过 API 公开(并且您无法从扩展程序访问该页面)。
可能可以通过 Dev Tools 扩展(访问网络事件)或 chrome.debugger
API(相同数据)获得特定页面的近似值通过不同的界面)。但它只会在“重新加载此页面以查看统计信息”的情况下起作用,并且再一次,将比网络级别实际发生的事情更抽象。
关于javascript - 如何从 Chrome 扩展中获取浏览器消耗的流量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45915877/