Dynamically save . html file with Javascript

Asked

Viewed 94 times

-3

I am creating a code editor (Javascript and HTML with iframe) where I need to save a file .html dynamically with Javascript. How can I do this?

<HTML> <HEAD> 

<SCRIPT language="JavaScript">
function escreverArquivo() {  

var fso  = new ActiveXObject("Scripting.FileSystemObject");

var fh = fso.CreateTextFile("c:Teste.txt", true); 

fh.WriteLine("Coloque todo o conteudo que voce deseja nesse trecho...");

fh.Close(); 

}

</SCRIPT></HEAD>
<BODY>

<P><SCRIPT language="JavaScript">  escreverArquivo(); </SCRIPT></P>

</BODY></HTML>

I found this code, but it only appears to save .txt.

  • 2

    Welcome to Stackoverflow. As far as I know, Javascript, running in browser, is not allowed to write files to the hard drive automatically. You can create an HTML file, and download it on the page. I recommend taking a look at this question, which has a great example where the user does it. https://stackoverflow.com/questions/3665115/how-to-create-a-file-in-memory-for-user-to-download-but-not-through-server

  • 1

    The API ActiveXObject is obsolete and therefore should not be used. Moreover, as mentioned in the previous comment, JS (in browser) is not allowed to manage the file system.

1 answer

0


Reply published by the questioner in the wrong place.

for those who came for the solution:

var textToSave1 = document.getElementById("código").value;
                var textToSaveAsBlob1 = new Blob([textToSave1], {type:"text/plain"});
                var textToSaveAsURL1 = window.URL.createObjectURL(textToSaveAsBlob1);
                var fileNameToSaveAs = "olamundo.html";//qualquer arquivo
                var downloadLink = document.createElement("a");
                downloadLink.download = fileNameToSaveAs;
                downloadLink.innerHTML = "Download File";
                downloadLink.href = textToSaveAsURL1;
                downloadLink.onclick = destroyClickedElement;
                downloadLink.style.display = "none";
                document.body.appendChild(downloadLink);
                downloadLink.click();
            }
function destroyClickedElement(event){
            }
  • just need to change some things(id and name)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.