javascript - 如何从 Chrome 扩展中获取浏览器消耗的流量?

标签 javascript google-chrome google-chrome-extension

我尝试使用这个 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/

相关文章:

javascript - 为什么我的 Chrome 扩展中从未收到过 onCreated 事件的选项卡会收到 webNavigation.onCompleted 事件?

javascript - 似乎不能在函数中使用 var 两次

google-chrome - 如何摆脱新的 chrome devtools 标尺?

css - 背景大小转换在 chrome 中停止工作

html - Firefox 和 Windows 中的 CSS 水平菜单问题

linux - 构建 Google Chrome NaCl 应用程序 .nexe 文件时找不到有效的库

javascript - 如何更改 chrome-extensions 中的所有相关图标

javascript - 在第一个脚本完成后 1 秒结束脚本

javascript - css/javascript 默认开始淡出,然后淡入

javascript - 使用返回函数和调用函数有什么区别