console.log("background.js started"); var baseUrl = ""; function getCurrentDate() { let today = new Date(); let yyyy = today.getFullYear(); let mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0! let dd = String(today.getDate()).padStart(2, '0'); return yyyy + mm + dd; } function onSuccess(result) { console.log(`background.js: onSuccess(): Promise resolved with result '${JSON.stringify(result)}'`); } function onFailure(error) { console.log(`background.js: onFailure(): Promise rejected with error '${error}'`); } // actually download an attached file async function downloadFile(url, filename, saveAs=false) { console.log(`background.js: downloadFile(): url is '${url}' and filename is '${filename}'`); return browser.downloads.download({ url: new URL(url, baseUrl).toString(), filename: filename, saveAs: saveAs // raise a path chooser dialog if true }); } // sequentially initiate download for each attached file async function downloadAllFiles(date, urlsAndFilenames) { for (let i = 0; i < urlsAndFilenames.length; i++) { // prefix filename let prefixedFilename = date + " " + urlsAndFilenames[i].filename; console.log(`background.js: downloadAllFiles(): i is ${i}`); await downloadFile(urlsAndFilenames[i].url, prefixedFilename, true).then(onSuccess, onFailure); } } // page action handler function handlePageactionClick(tab) { console.log("background.js: handlePageactionClick(): sending message"); // get base url browser.tabs.query({currentWindow: true, active: true}) .then(tabs => { console.log(`background.js: handlePageactionClick(): tab query returned ${JSON.stringify(tabs)}`); baseUrl = tabs[0].url; }) // send message to content script which will trigger said content script browser.tabs.sendMessage(tab.id, "pageAction was clicked") .then(message => { console.log(`background.js: received a response from contentscript.js with content ${JSON.stringify(message.urlsAndFilenames)} | ${JSON.stringify(message.date)}`); downloadAllFiles(message.date, message.urlsAndFilenames); }) .catch(error => console.error(`background.js: handlePageactionClick(): The following error occured while handling a page action: ${error}`) ) } // add listener for the extension button browser.pageAction.onClicked.addListener(handlePageactionClick);