1

I need a function that will download the string in a javascript variable into a text file(5-7MB). The function should work across browsers.

I've tried making such a download function, but it doesn't work on Chrome. FireFox opens the 'save' dialog box, but Chrome doesn't. Also, when I disable 'ask where to save file' in Chrome, it shows 'Failed - Network Error'. Since I'm doing everything locally, I don't see why this issue crops up.

function download(filename, text) {
 var element = document.createElement('a');
 element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
 element.setAttribute('download', filename);

 element.style.display = 'none';
 document.body.appendChild(element);

 element.click();

 document.body.removeChild(element);

}

This doesn't open any dialog box for saving a file on Chrome(Version 76.0.3809.132). Same issue for Microsoft Edge(44.17763.1.0). I want it to work on all browsers, or at least work on FireFox and Chrome.

Edit 1: The Chrome issue seems to persist on other computers, so it can't be something wrong with the browser. I would also prefer to make my own function rather than use other projects(company issues).

Edit 2: It seems that the anchor size is limited to 2MB in Chrome. Is there a workaround for this? There are some answers that recommend using BLOB, but I'm not familiar with the concept. Any explanation would be appreciated.

the_ritz
  • 322
  • 2
  • 17
  • I use this: https://github.com/eligrey/FileSaver.js , example for saving text to file is on repo: `var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"}); FileSaver.saveAs(blob, "hello world.txt");` – user1063287 Aug 29 '19 at 12:02
  • 1
    This answer https://stackoverflow.com/a/38845151/6458902 may help you if your issue is related to the file size. – Sackey Aug 29 '19 at 14:23
  • @Sackey Thanks for the link, it seems that there is no way to use the anchor for downloading files greater than 2MB. – the_ritz Aug 30 '19 at 05:28

2 Answers2

2

I found a simple modification that now works on my FireFox and Chrome. It uses BLOB to get around the anchor size limit. It still doesn't work on Microsoft Edge though.

function download(filename, text, type="text/plain") {
  // Create an invisible A element
  const a = document.createElement("a");
  a.style.display = "none";
  document.body.appendChild(a);

  // Set the HREF to a Blob representation of the data to be downloaded
  a.href = window.URL.createObjectURL(
    new Blob([text], { type })
  );

  // Use download attribute to set set desired file name
  a.setAttribute("download", filename);

  // Trigger the download by simulating click
  a.click();

  // Cleanup
  window.URL.revokeObjectURL(a.href);
  document.body.removeChild(a);
}
the_ritz
  • 322
  • 2
  • 17
0

If this icon appears in your address bar

Disabled automatic downloads picture

then check your Chrome config to enable automatic downloads.

Sackey
  • 392
  • 2
  • 11