/ Gists / Download file via JavaScript
On gists

Download file via JavaScript

JavaScript

download.js Raw #

// https://javascript.plainenglish.io/how-to-download-a-file-using-javascript-fec4685c0a22

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('target', '_blank');
      aElement.click();
      URL.revokeObjectURL(href);
    });
};


downloadFile('https://www.google-analytics.com/analytics.js', 'gooleAnalytics.js')