Implementing FileSaver.js saveAs() function into HTML script

15.3k views Asked by At

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:

//some irrelevant text

<script src="FileSaver.js">
  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>

//some more irrelevant text

<input type="button" value="download" onclick="download();"/>
/*from this button I want to gather information from input text fields on the page.
 I already know how to do that, the problem is creating and, subsequently, 
downloading the text file I am trying to create. For simplicity's sake, the text I am 
capturing in this example is hardcoded as "hello world"*/

//last of irrelevant text
//oh, and don't try to run this snippet :P

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

1

There are 1 answers

2
Ruan Mendes On BEST ANSWER

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>