0

HI I am creating a dynamic html section and I have two buttons: preview and download.

The preview is fine working. As for the second button, i.e. download, I want to make the action of the button such that if the download button is clicked, it triggers a download of all html code stored in the variable rohit with .html format.

How do I do this? Please let me know. I had searched for it on Google but could not find a way to do it.

$(document).ready(function(){
  var rohit = "<h2>Hello i m Dynamic Heading </h2>";
     $('.preview').on('click', function(){
            var myWindow = window.open('', "rohit", "width=800, height=400", '_blank');
   myWindow.document.write(rohit);
        });
    
    
     $('.download').on('click', function(){
         alert(rohit);
            //  here download code with html format how to do this .
        });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<button class="preview">click to preview</button>
<button class="download">CLick to Download</button>

and Jsfiddle Link here

Acharya Anurag
  • 671
  • 6
  • 23
Rohit Azad Malik
  • 31,410
  • 17
  • 69
  • 97

2 Answers2

1

In short: you need to use Blob.

For more info and demo:

Save/download data generated in JavaScript.
Demo.

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
1

Most likely what you have to do is to change the headers of you request to be:

Content-Type: application/octet-stream
Content-Disposition: attachment; filename="file.html"

That will tell the browser to download your file.

Alejandro Garcia Anglada
  • 2,373
  • 1
  • 25
  • 41