Supriya
Supriya

Reputation: 288

Download a Table content (string) from Html Page without the need of a physical file

I am generating some important information on the HTML page at the end of a transaction.

<html>
<head>
  <script type="text/javascript">
    function downloadReference(){
    }
  </script>
</head>
<body>
  <p>
  Hello! Thank you for your interest.
  </p>
  <table style="background-color:#ccffcc;border: 1px solid #00cc00" id="referencedata">
    <tr>
        <td><b>Interest Received Date:</b></td>
        <td>22 March 2018</td>
    </tr>
    <tr>
        <td><b>Confirmation Number:</b></td>
        <td>J4835K3344</td>
    </tr>
  </table>
  <br/>
  <a href="#" onclick="return downloadReference();" download="Reference.html">Download this info!</a>
</body>
</html>

Now, I want give user an option to download this info for his reference. I don't want to create a file at server side.

I know in HTML5 we can give download attribute in anchor tag to allow user to download the file, but how do I generate the content on the fly and not refer to any physical file?

Upvotes: 1

Views: 739

Answers (2)

pj100
pj100

Reputation: 402

You can do something like this which would be pretty simple. You're going to need to pass your data into a data url at some point. if it's rendered with JS I would recommend passing the data to a function like in my example below and using a listener instead of onclick. Otherwise, you could encode it into a data attribute on your link and pass it in that way. I'm happy to update to better explain.

function generateFile(dataurl, filename) {
  // create a hidden anchor
  var link = document.createElement("a");
  link.href = dataurl; 
  link.setAttribute("download", filename); 
  // programatically click dynamic anchor
  var mouse = document.createEvent("MouseEvents");
  mouse.initEvent("click", false, true);
  link.dispatchEvent(mouse);
  return false;
}

document.getElementById('download').onclick = function() {
  generateFile("data:text/html, <h1>Your HTML</h1>", "reference.html");
}

Upvotes: 0

Supriya
Supriya

Reputation: 288

Thanks to @bloodyKnuckles for the hint. Writing answer for anyone who's need this in future.

I added id to my anchor tag:

<a href="#" id="dl"...

Then, JavaScript function:

function downloadReference(){
     var dl = document.getElementById ("dl");
     dl.href="data:text/plain," + document.getElementById("data").outerHTML;
     return true;
}

return true; is required for download to happen.

We don't support dead browsers like IE, so no worries about that.

Upvotes: 1

Related Questions