admin管理员组

文章数量:1287485

Is it possible to create and download a .txt file using only JavaScript (no server-side programming !), and save it on local drive, without displaying browser "Save file" dialog ?

Is it possible to create and download a .txt file using only JavaScript (no server-side programming !), and save it on local drive, without displaying browser "Save file" dialog ?

Share Improve this question asked Sep 13, 2014 at 18:55 user2405219user2405219 1511 gold badge2 silver badges12 bronze badges 7
  • 9 Imagine a world where any webpage could write to your local file system without asking you... – David Commented Sep 13, 2014 at 18:56
  • Well, you can store texts in localstorage or in a sandboxed filesystem, but not directly on a specific drive. – Bergi Commented Sep 13, 2014 at 19:00
  • 1 it's easy, others on here so far are wrong. use danml./download.html if you want to save many files, you have to confirm once after the 2nd or 3rd download, but then you can download all day without further clicks. – dandavis Commented Sep 13, 2014 at 19:20
  • 1 @Bergi - There is no sandboxed filesystem. The previous File System API has been cancelled and should not be referenced. – Derek 朕會功夫 Commented Sep 13, 2014 at 19:28
  • @dandavis: None of the examples there work for me without showing a file-save dialog. And it would be very unintuitive anyway. – Bergi Commented Sep 14, 2014 at 13:52
 |  Show 2 more ments

2 Answers 2

Reset to default 8

Rickard Staaf's answer is outdated. To download a file in javascript locally without prompting a dialog box, be sure to enable it in your browser settings (chrome >> settings >> advanced >> downloads and turn off 'Ask where to save each file before downloading'.

Subsequently, you can write a simple text file like so using blob objects:

function save() {
  var content = ["your-content-here"];
  var bl = new Blob(content, {type: "text/plain"});
  var a = document.createElement("a");
  a.href = URL.createObjectURL(bl);
  a.download = "your-download-name-here.txt";
  a.hidden = true;
  document.body.appendChild(a);
  a.click();
}

No not without browser plugins, that would be a big security risk.

本文标签: Download txt using JavaScript without dialog promptStack Overflow