console.log("contentscript.js started!"); 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 extractFileUrlsAndNames() { console.log("contentscript.js: this is extractFileUrlsAndNames()"); // get the correct frame let frame = document.querySelector("iframe.js-mail-content"); // get all divs containing attachments let divs = frame.contentWindow.document.body.querySelectorAll("div.samoware-mail-message__attach__item[attachment-ref]"); console.log(`contentscript.js: found ${divs.length} div containing attachments`); let urlsAndFilenames = [] // loop over divs and extract attachment information divs.forEach(div => { let url = div.getAttribute("attachment-ref"); let filename = div.getAttribute("file-name"); // if filename is null, derive it from url if ( ! filename ) { let splitUrl = url.split("/"); filename = splitUrl[splitUrl.length-1]; } urlsAndFilenames.push({url: url, filename: filename}); }) //console.log(`contentscript.js: urlsAndFilenames is ${JSON.stringify(urlsAndFilenames)}`); return urlsAndFilenames; } function onStartedDownload(id) { console.log(`contentscript.js: Started downloading: ${id}`); } function onFailedToStartDownload(error) { console.log(`contentscript.js: Download failed: ${error}`); } // get today's date let currentDate = getCurrentDate(); console.log(`contentscript.js: currentDate is ${currentDate}`); let urlsAndFilenames = extractFileUrlsAndNames(); // loop over attachments for (let i = 0; i < urlsAndFilenames.length; i++) { // prefix filename let prefixedFilename = currentDate + " - " + urlsAndFilenames[i].filename; console.log(`contentscript.js: prefixedFilename is ${prefixedFilename}`); // start download let downloading = browser.downloads.download({ url: urlsAndFilenames[i].url, filename: prefixedFilename, saveAs: i == 0 // raise a path chooser dialog for the first file only; all later files will (hopefully!) be saved to the same folder }); console.log(`contentscript.js: downloading is ${downloading}`); // resolve Promise downloading.then(onStartedDownload, onFailedToStartDownload); } console.log("contentscript.js: has finished"); "contentscript.js: this is the final line";