Create text file in JavaScript

I am trying to create a text file using JavaScript, I know that this is possible with an ActiveX object, but it only works well in IE browsers.

My requirement is to generate a text file using JavaScript for Safari browsers?

Can anyone help me in this regard?

+8
javascript browser file safari
source share
3 answers

Another way to do this is to use Blob and URL.createObjectURL . All recent browsers, including Safari 6+, support them.

 var textFile = null, makeTextFile = function (text) { var data = new Blob([text], {type: 'text/plain'}); // If we are replacing a previously generated file we need to // manually revoke the object URL to avoid memory leaks. if (textFile !== null) { window.URL.revokeObjectURL(textFile); } textFile = window.URL.createObjectURL(data); // returns a URL you can use as a href return textFile; }; 

Here is an example that uses this method to save arbitrary text from textarea .

One more note that I used the download attribute in the download link. Unfortunately, Safari does not currently support it. However, in browsers, the file is automatically loaded when clicked, and not in opening the file in the browser. In addition, since I set the download attribute to info.txt , the file will be loaded with that name instead of the random name generated by createObjectURL .

+12
source share

In JavaScript, you can use the following line to ask the user to save a text file,

window.open("data:text/json;charset=utf-8," + escape("Ur String Object goes here"));

I tested this several times in some popular browsers ... just make sure it works in Safari or not. Luck

+8
source share

but my requirement is to generate a text file using javascript for Safari browser

This is not possible with vanilla Javascript due to security restrictions. However, you can use server-side javascript such as Node.JS or Ajax, or some other server technology.

-2
source share

All Articles