How to write a local .txt with Javascript

2019-06-09 17:12发布

问题:

I want to write a .txt file using the javascript console in IE. I already have the strings that I would like to write on the file; so, what I would like to do is:

var refTab=document.getElementById("historymatch_tb0");
var  ttl;
for ( var i = 0; row = refTab.rows[i]; i++) 
{
   row = refTab.rows[i];
   for ( var j = 0; col = row.cells[j]; j++ )
   {
       WriteInFile (col.innerHTML);
   }

}

What I don't have is the function WriteInFile because I triyed this:

 function WriteInFile (a)
 {
  var fso = new ActiveXObject("Scripting.FileSystemObject");
  var filename = "c:\\Users\\Riccardo\\a.txt";
  var f = fso.OpenTextFile(filename, 2, true); 
  f.WriteLine(a);
  f.Close();
  }

this doesn't works, The script doesn't give me errors but the file is empty and The console shows the word: undefined! Where is the problem? Thanks!

回答1:

Since HTML5 this is possible. See http://www.w3.org/TR/file-writer-api/#the-filesaver-interface and http://eligrey.com/blog/post/saving-generated-files-on-the-client-side



回答2:

If I am understanding you correctly, what you are really asking is for a way to persist information in js between sessions. I understand how a file looks great for that task. But since browsers have a very limited access to the filesystem, that is not ideal.

Instead of using a local file, you can persist the information you need in the browser's Web Storage. You can come later and retrieve it. See http://www.html5rocks.com/en/features/storage for details



回答3:

Maybe it's some browser issue ? I tried in IE9 - it works correctly (see jsfiddle - it's your code)

 var a = "Hello";
 WriteInFile(a);

http://jsfiddle.net/nb5N7/1/

But, also I must enable not safe activeX execution

http://social.msdn.microsoft.com/Forums/vstudio/en-US/41b3a68b-dd16-48a8-b86c-02a1e543081c/activexobjectscriptingfilesystemobject-automation-server-cant-create-object (see answer)

UPD: why you are minused me ? UPD2:

for ( var i = 0; row = refTab.rows[i]; i++) 

maybe possible issue here ? you should write

 var i = 0; i < refTab.rows.lenght; i++

instead of

 for ( var i = 0; row = refTab.rows[i]; i++) 

and, also, try add alert(1); to for cycle (to check is it work correctly)