Implementing FileSaver.js saveAs() function into HTML script

MasterChef picture MasterChef · Jun 19, 2015 · Viewed 12.4k times · Source

Right now I am attempting to save information from an HTML page that I am creating to a text document, using javascript and the FileSaver.js package. I am not very well versed in HTML and am completely new to javascript, so odds are that I am making some egregious mistake. At the moment, I have eligrey's FileSaver.js file in the same directory as the HTML file that I am working from, so I should be able to call it simply as "FileSaver.js" in HTML.

Right now I am working from something like this:

I also have eligrey's Blob.js file available in my immediate working directory as well, just in case.

As of now, the button does nothing. I am fairly sure that I am calling the function correctly considering I could receive the javascript alert text, at least when the script tag had no src. If I do add a src, absolutely nothing happens. The browser that I am testing from is the latest Google Chrome stable build (43.0 I think) on Windows XP. Please inform me of anything that I am missing and/or doing wrong. Thanks in advance

Answer

Juan Mendes picture Juan Mendes · Jun 19, 2015

You cannot have a script tag with a src attribute and content inside the tag. Split it into two separate script tags. See What if script tag has both "src" and inline script?

Note that <script> cannot be a self-closing tag

<script src="FileSaver.js"></script>
<script>
  function download(){

    //alert("hello world");
    //this alert line was to test the function call
    //the alert actually appears when the <script> tag
    // has no src field labeled. Just an observation.

    var blob = new Blob(["Hello World"],{type:"text/plain;charset=utf-8"});
    saveAs(blob,"helloworld.txt");
   }
</script>