0

I want to be able to use an extension to download a file and memorize the downloadId for later use. My original attempt at doing this was by using the callback function and assigning the downloadId as a variable like this:

chrome.downloads.download({
    url: downloadURL
},
    function getDownloadId(downloadId) {
        var thisDownloadId = downloadId;
    }
);

But this caused my Chromebook to crash, so I don't think that will work.

I attempted to use the solution from this question. However, when I attempt to use said solution, it ended up in this error:

TypeError: Cannot read property 'current' of undefined.

This is the snippet of my script that downloads the file (popup.js)

chrome.downloads.download({
    url: downloadURL
});

And the snippet of where it waits for the file to download, which currently only displays the downloadId for testing (popup.js)

chrome.downloads.onChanged.addListener(function (
    if(detail.state.current == "complete") { // This is where the error occurs
        var downloadId = detail.id;

        alert("downloadId: " + downloadId);
    }
});
  • Currently you're creating the variable inside the callback function so it's immediately destroyed when the function finishes. Depending on how exactly you want to use the id later, you can save it in chrome.storage.local or localStorage (as a string), look for examples. – wOxxOm Oct 30 '19 at 05:14
  • Thank you, wOxxOm! This comment helped me a lot. I never thought of using the chrome.storage API. – enthusiasticGeek Oct 30 '19 at 23:19

1 Answers1

0

The downloadId variable was getting destroyed due to it being in a callback function. I needed to use the chrome.storage api to get it out.

The download function (modified)

chrome.downloads.download({
    url: downloadURL
},
    function(downloadId) {
        chrome.storage.local.set({'downloadId': downloadId}, function() {
            console.log("Store Download ID.");
            chrome.storage.local.set({'downloadId': downloadId});
        })
    }
);

The downloadId alert function:

chrome.storage.local.get(['downloadId'], function(result) {
    var downloadId = result.downloadId;
    alert(downloadId);
});