Reputation: 1001
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);
}
}
Upvotes: 2
Views: 4389
Reputation: 77523
You can't do so in an event-based way.
From onChanged
documentation (emphasis mine):
When any of a
DownloadItem
's properties exceptbytesReceived
andestimatedEndTime
changes, this event fires with thedownloadId
and an object containing the properties that changed.
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);
}
});
}
Upvotes: 6