0

I am getting a server response like as below and I want to create an html file using javascript and save it on the local machine.

HTML File

  <!DOCTYPE html>
    <html>
    <head>
     <script>
    function copyText()
    {
    }
    </script>
    </head>
    <body>

    Field1: <input type="text" id="field1" value="Hey There"><br>
    Field2: <input type="text" id="field2">
    <br><br>
    <button onclick="copyText()">Copy Text</button> 

    <p>A function is triggered when the button is clicked. The function copies the text from Field1 into Field2.</p>

    </body>
    </html> 

Is it possible to create a file using javascript?

I tried to use

 fso = new ActiveXObject("Scripting.FileSystemObject");
                                            thefile=fso.CreateTextFile("C:\\tmp\\MyFile.txt",true);
write(responseHtmlStr)

on chrome but I got the error 'Uncaught ReferenceError: ActiveXObject is not defined '

I read somewhere that it is not possible due to security threat. Please give some pointers. It would be very helpful.

Thank you Gendaful

Anderson Pimentel
  • 5,086
  • 2
  • 32
  • 54
Gendaful
  • 5,522
  • 11
  • 57
  • 76
  • 1
    @MikyDinescu: That's [not strictly true](http://www.html5rocks.com/en/tutorials/file/filesystem/). – josh3736 Mar 12 '13 at 18:13
  • My issue is I am getting a big html in the server response that I need to display in an iFrame. Since iFrame takes only url as the I/P, I have to write the server response to the file and store it somewhere so I can give that url in iFrame 's src attribute and display it. Are there any other alternatives? – Gendaful Mar 12 '13 at 18:14
  • @josh3736 - yep, you're right. What I should have said is: it's not possible to create _arbitrary_ files on the file system.. – Mike Dinescu Mar 12 '13 at 18:17

2 Answers2

1
  1. To answer your first question: No, you can't. Imagine I made a website that replaces C:\WINDOWS\windows.exe with a virus by javascript. That would be so uncool that the creators of browsers/javascript made it impossible.

  2. "Are there any other alternatives?"

Yes, use jQuery ajax to load the contents if it's on the same server

Or, use php curl to load the contents if it's not on same server (+ajax propably)

Jacek Pietal
  • 1,980
  • 1
  • 18
  • 27
0

Sorry, but just as you said yourself, you cannot create files on the local machine using JavaScript because of security issues like viruses being written to your system. I would recommend looking at all of the similar answers to this question - it has been asked many times on SO.

imulsion
  • 8,820
  • 20
  • 54
  • 84
  • Hi imulsion. I tried http://stackoverflow.com/questions/585234/how-to-read-and-write-into-file-using-javascript but somehow the file is not getting created in the C:// . Any reasons you foresee? – Gendaful Mar 12 '13 at 19:20
  • not really unless I see the code u wrote... :/ – imulsion Mar 13 '13 at 17:33