简体   繁体   中英

How to create a file in an offline html project using JavaScript [on hold]

How do I create three individual files with the button onclick function and save it to internal storage. I am not running the code on a server but inside an ide. My intention is to build my own ide that looks like codepen. The project is very basic and it is working offline not online. I am going make it an app for for android phones.


  
  
  
<!Doctype html>
  <html>
 <head>
    <title>HTML editor</title>
      <head>
   <body>
<div>
   <textarea Id="html"></textarea>

<textarea Id="css"></textarea>

<textarea Id="js"></textarea>

    <!--Add iframe to display to display results-->

       <iframe id="code"></iframe>
 <button onclick="Create_and_Save()">Save</button>

<script>
function compile(){

var html = document.getElementById("html");

var css = document.getElementById("css");

var js = document.getElementById("js");

var code = document.getElementById("code"). contentWindow.document;

try{
document.body.onkeyup = function (){
code.open();
code.writeIn(html.value + "<style>" + css.value + "</style>" + "<script>" + js.value + "</style>" );
code.close();
}

}//End of try...

catch(err){
alert(err);
}

}//End of compile..

compile();

</script>

<script>

function Create_and_Save(){

var html = document.getElementById("html").value;

var css = document.getElementById("css").value;

var js = document.getElementById("js").value;

//What I want to achieve is to create three individual file with their extensions.
//.html
//.css
//.js
//when I click the button.
}
</script>
</body>
</html>

If you're trying to create and save a file without user interaction, then browsers don't allow that for security reasons.

If a "Save As" dialog is good enough for your solution, this might be a relevant answer for that .

First you base64 encode the content if your textarea ( https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding ) and then you add this encoded content to a link and stream it... as described here: https://stackoverflow.com/a/3665147/2397550 . An example of such a link is shown below:

 <a href="data:application/octet-stream;charset=utf-16le;base64,//5mAG8AbwAgAGIAYQByAAoA">text file</a>

The octet-stream is to force a download prompt. Otherwise, it will probably open in the browser. Source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM