Shi*_*tal 1 jquery google-chrome google-chrome-extension
我正在创建一个 chrome 扩展来监控下载进度。我能够捕获下载开始和下载完成事件,但不知道如何获取更改的进度?请帮忙。下面是我的下载监听器
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);
}
}
Run Code Online (Sandbox Code Playgroud)
您不能以基于事件的方式执行此操作。
来自onChanged文档(强调我的):
当 a 的任何
DownloadItem属性(除了bytesReceived和 )estimatedEndTime发生更改时,此事件会随着downloadId和 包含已更改属性的对象而触发。
这意味着 Chrome 不会针对下载进度触发事件,这是有道理的:这种变化非常频繁,您不希望在每个网络数据包之后触发事件。
您可以以合理的速率(即有活动下载时每秒一次)查询进度,如下所示:
// 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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4110 次 |
| 最近记录: |