Trigger a file download on click of button Javascript with contents from DOM

后端 未结 3 1674
失恋的感觉
失恋的感觉 2021-01-22 05:00

I want to download a file which is created from DOM element. So a user clicks a button on web page and it invokes a javascript method which may grab the contents of DOM element

相关标签:
3条回答
  • 2021-01-22 05:24

    I am not sure if I understand correctly what is the content that you are trying to download. If you have the content (which sounds like the HTML of an element?) stored in a variable, you can try:

    ("#downloadbutton").click(function() {
      //var content = content of file;
      var dl = document.createElement('a');
      dl.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(content));
      dl.setAttribute('download', 'filename.txt');
      dl.click();
    });
    
    0 讨论(0)
  • 2021-01-22 05:27

    I appreciated finding this question, but at least on Firefox running with linux, you need to append the dl element to the document to get the click functionality to work. I haven't tested extensively on other browsers how necessary this is, but it is necessary on some at least, so I recommend the following modification:

    var content = document.getElementById("elem").innerHTML;
    var dl = document.createElement('a');
    dl.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(content));
    dl.setAttribute('download', 'filename.txt');
    // Set hidden so the element doesn't disrupt your page
    dl.setAttribute('visibility', 'hidden');
    dl.setAttribute('display', 'none');
    // Append to page
    document.body.appendChild(dl);
    // Now you can trigger the click
    dl.click();
    
    0 讨论(0)
  • 2021-01-22 05:45

    Figured it out: I had to do `

    function myAlert(){
        var content = document.getElementById("elem").innerHTML;
        var dl = document.createElement('a');
        dl.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(content));
        dl.setAttribute('download', 'filename.txt');
        dl.click();
    }
    
    document.addEventListener('DOMContentLoaded', function () {
        document.getElementById('alertButton').addEventListener('click', myAlert);
    });
    
    0 讨论(0)
提交回复
热议问题