如何在Chrome扩展程序中捕获下载进度 [英] How can i capture the download progress in chrome extension
问题描述
我正在创建一个Chrome扩展程序,以监视下载进度.我能够捕获下载开始和下载完成事件,但是不知道如何获得更改的进度?请帮忙. 下面是我的下载监听器
I am creating a chrome extension which moniters the download progress. I am able the capture the download begin and download complete events but have no idea on how to get the changed progress? Please help. Below is my download listener
function AddDownloadListener() {
//--------------------------------------------------------------------------------------------------------------
chrome.downloads.onCreated.addListener(DownloadCreated);
chrome.downloads.onChanged.addListener(DownloadChanged);
function DownloadCreated(el) {
console.log("Download Begins");
console.log(el);
mobjPortToFoxtrot.postMessage({ message: "Download Begins", element: el });
}
//--------------------------------------------------------------------------------------------------------------
function DownloadChanged(el) {
if (el.danger === undefined || el.danger == null) {
console.log(el.state.current);
mobjPortToFoxtrot.postMessage({ message: el.state.current, element: el });
}
else {
console.log("dangerous content");
mobjPortToFoxtrot.postMessage({ message: "dangerous content", element: el });
}
console.log(el);
}
}
推荐答案
您不能以基于事件的方式进行操作.
You can't do so in an event-based way.
来自 onChanged
文档(重点是我):
From onChanged
documentation (emphasis mine):
DownloadItem
的任何属性(bytesReceived
和estimatedEndTime
除外)发生更改时,都会触发downloadId
和包含更改属性的对象.
When any of a
DownloadItem
's properties exceptbytesReceived
andestimatedEndTime
changes, this event fires with thedownloadId
and an object containing the properties that changed.
这意味着Chrome不会为下载进度触发事件,这是有道理的:这种变化非常频繁,您不希望在每个网络数据包之后触发事件.
This means Chrome will not fire events for the download progress, which kind of makes sense: this changes very frequently, you don't want an event fired after every network packet.
由您自行决定以合理的速率(例如,在进行有效下载时每秒)查询进度,如下所示:
It's up to you to query the progress with a sensible rate (i.e. every second while there is an active download) with something like this:
// Query the proportion of the already downloaded part of the file
// Passes a ratio between 0 and 1 (or -1 if unknown) to the callback
function getProgress(downloadId, callback) {
chrome.downloads.search({id: downloadId}, function(item) {
if(item.totalBytes > 0) {
callback(item.bytesReceived / item.totalBytes);
} else {
callback(-1);
}
});
}
这篇关于如何在Chrome扩展程序中捕获下载进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!