How can i capture the download progress in chrome extension

青春壹個敷衍的年華 提交于 2019-12-25 16:57:30

问题


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);
    }
}

回答1:


You can't do so in an event-based way.

From onChanged documentation (emphasis mine):

When any of a DownloadItem's properties except bytesReceived and estimatedEndTime changes, this event fires with the downloadId 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);
    }
  });
}


来源:https://stackoverflow.com/questions/26179686/how-can-i-capture-the-download-progress-in-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!