本文介绍了Chrome webRequest onCompleted:页面大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Chrome扩展程序,我想知道是否有一种方法可以知道在加载页面时下载的数据量.

I am working on a Chrome Extension, and I wanted to know if there was a way to know the amount of data which has been downloaded while loading a page.

例如,如果用户激活了扩展程序并使用Google.com,则我想向他显示页面大小:google.com.

For example, if the user activates the extension, and goes on Google.com, I want to show him the size of the page: google.com.

有没有办法做到这一点?

Is there a way to do this?

谢谢!

推荐答案

有多种方法可以仅使用JavaScript来确定页面的大小.

There are a multitude of ways you could determine the size of a page using just javascript.

  1. 您可以通过计算页面和脚本中字符的数量来手动计算页面的大小.下面的示例脚本计算了一个ascii编码的html doc的大小(因此不包括图片,来自url的脚本等).我不太确定这是多么准确或快速,所以不要在上面引用我.

示例脚本:

var html=document.getElementsByTagName('HTML')[0].outerHTML,//get all html as string
    sizeKB=a.length/1024;//assuming the page is encoded in ascii, each char is one byte, 1024 bytes = 1 kb

对于确定图像的大小,此问题可能会有所帮助:确定图像文件的大小+通过Javascript标注尺寸?

For determining size of images, this question could help: Determining image file size + dimensions via Javascript?

  1. 您可以使用Google的 pagespeed洞察力 pingdom .您可以尝试在后台页面的iframe中加载服务,并使用内容脚本输入网址并提取网站的统计信息并将其发送到弹出窗口.我确定还有很多其他服务可以帮助您完成ajax调用,尽管我对此一无所知.

  1. You could load the results using another service like google's pagespeed insights or pingdom. You could try to load the services in an iframe in your background page and use content scripts to input the url and extract the site's statistics and send them to the popup. I'm sure plenty of other services could help you do the same with ajax calls although I don't know of any.

使用ajax和jquery,您可以确定页面中所有资产的大小并将它们添加在一起:.如果使用得当,可以从捕获中获取所有文件,因此不会占用更多网络资源.但是对于具有很多非嵌入式脚本,样式表和图像的页面来说,速度可能会有些慢

Using ajax and jquery, you could determine the size of all the assets in the page and add them together: Get size of file requested via ajax . Used correctly, this could fetch all of the files from the catch, so it wouldn't use more of the network. But it might be a bit slow for pages with a lot of non-inline scripts, stylesheets, and images

使用 chrome.webrequest API,您可以获取标头'Content-Length'确定文件大小.我也没有测试过该脚本,所以请告诉我它是如何工作的.如果缺少标题,请确保进行后备!

Using the chrome.webrequest api, you could get the header 'Content-Length' to determine the file size. I haven't tested this script also, so tell me how this works. Make sure to have a fallback if the header is missing!

示例脚本:

chrome.webRequest.onHeadersReceived.addListener(
function(details){
    var fileSize;
    details.responseHeaders.forEach(function(v,i,a){
        if(v.name == 'Content-Length')
            fileSize = v.value;
    });
    if(!fileSize)//if Content-Length header is missing fall back to another method of calculating file size
        fallBackGetFileSize(details);
},
{urls: ["http://*/*"]},["responseHeaders"]);

这篇关于Chrome webRequest onCompleted:页面大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 06:14