init.js

console.log('init');

/**
 * This file sets up the downloads.onChanged listener. 
 * It handles the creation of the download picker based upon the download that is being performed. 
 * The loading of the Download Picker view is handled by the DownloadPicker class
 */


try {
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; 
window.directoryEntry = window.directoryEntry || window.webkitDirectoryEntry;
browser.downloads.onChanged.addListener(
    function(delta){
        browser.downloads.search({id:delta.id})
        .then(function(items){

            const downloadItem = items[0];
            console.log(downloadItem);
            return;
        });
        
    }
)
} catch (e){console.log(e);}

class DownloadManager {

    constructor(){
        this.downloads = {};
    }
    register(){
        browser.downloads.onCreated.addListener(this.downloadStarted.bind(this));
    }

    downloadStarted(delta){
        browser.downloads.search({id:delta.id})
        .then(function(items){
            this.downloadItem(items[0]);
        }.bind(this));
    }
    downloadItem(downloadItem){
        if (this.downloads[downloadItem.url]!=null
            &&downloadItem.filename.endsWith(this.downloads[downloadItem.url].filename))return;

        const myDownload = {url:downloadItem.url, filename:downloadItem.filename};
        this.downloads[downloadItem.url] = myDownload;
        const picker = new DownloadPicker(myDownload);
        picker.show();
    }
}

const dm = new DownloadManager();
dm.register();

browser.runtime.onMessage.addListener(
    function(msg){
        try {
            browser.downloads.download({
                url: msg.url,
                filename: msg.filename
            });
        } catch(e){console.log(e);}
    }
)