I don't have much JS experience but thought this should be fairly simple - still, can't get it to work. I need to download a file from an external server (AWS - no authentication, just plain url) when a web page loads (no clicks). Would have been nice to just use the HTML5 'download' attribute - but doesn't work in this case.
So, have tried various JS code snippets I found. Closest I got was:
function downloadFile(url, fileName){
fetch(url, { method: 'get', mode: 'no-cors', referrerPolicy: 'no-referrer' })
.then(res => res.blob())
.then(res => {
const aElement = document.createElement('a');
aElement.setAttribute('download', fileName);
const href = URL.createObjectURL(res);
aElement.href = href;
// aElement.setAttribute('href', href);
aElement.setAttribute('target', '_blank');
aElement.click();
URL.revokeObjectURL(href);
});
}
downloadFile('https://www.google-analytics.com/analytics.js', 'gooleAnalytics.js')
While this looks like it is working it actually downloads an empty file.
Ideas?
Cheers.
Trying to download a remote file on page load. Resulted in empty file being downloaded.