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}'`); } 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 }); } async function downloadAllFiles(urlsAndFilenames) { console.log(`background.js: downloadAllFiles(): started with ${JSON.stringify(urlsAndFilenames)}`); const currentDate = getCurrentDate(); for (let i = 0; i < urlsAndFilenames.length; i++) { // prefix filename let prefixedFilename = currentDate + " " + urlsAndFilenames[i].filename; console.log(`background.js: downloadAllFiles(): i is ${i}`); if ( i == 0 ) { await downloadFile(urlsAndFilenames[i].url, prefixedFilename, true).then(onSuccess, onFailure); } else { downloadFile(urlsAndFilenames[i].url, prefixedFilename, true).then(onSuccess, onFailure); } } } function handlePageactionClick(tab, onClickData) { console.log("background.js: handlePageactionClick(): executing content script"); // 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; } ) // execute content script browser.scripting.executeScript( { files: [ "/contentscript.js" ], target: { tabId: tab.id, allFrames: false } } ) .then(results => { console.log(`background.js: handlePageactionClick(): content script execution successful with results '${JSON.stringify(results)}'`); results.forEach(r => downloadAllFiles(r.result)); }) .catch(error => console.error(`background.js: handlePageactionClick(): The following error occured while executing a content script: ${error}`) ) } // add listener for the extension button browser.pageAction.onClicked.addListener(handlePageactionClick);