Cody Coderson
Cody Coderson

Reputation: 421

Download <div> content as html on firefox

I have a javascript that saves the contents of a <div> as html on click, which works just fine on chrome, but doesn't on firefox.

Please help me write a cross browser solution.

Here's my code:

$(window).load(function(){

function downloadInnerHtml(filename, elId, mimeType) {
    var elHtml = document.getElementById(elId).innerHTML;
    var link = document.createElement('a');
    mimeType = mimeType || 'text/plain';

    link.setAttribute('download', filename);
    link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(elHtml));
    link.click(); 
}

var fileName =  'invo.html';

$('#downloadLink').click(function(){
    downloadInnerHtml(fileName, 'Invoice','text/html');
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Invoice">
  CONTENT GOES HERE
</div>
<a href="#" onclick="return false;" id="downloadLink">Download</a>

Upvotes: 1

Views: 404

Answers (1)

myf
myf

Reputation: 11303

Apparently, simply adding the temporal link to document fixes the issue in Firefox; presumably Firefox doesn't like clicking elements that are not "in the page":

$(window).load(function(){

function downloadInnerHtml(filename, elId, mimeType) {
    var elHtml = document.getElementById(elId).innerHTML;
    var link = document.createElement('a');
    mimeType = mimeType || 'text/plain';

    link.setAttribute('download', filename);
    link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(elHtml));
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

var fileName =  'invo.html';

$('#downloadLink').click(function(){
    downloadInnerHtml(fileName, 'Invoice','text/html');
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Invoice">
  CONTENT GOES HERE
</div>
<a href="#" onclick="return false;" id="downloadLink">Download</a>

Btw, in this case, you could re-use the original "button" link to hold the download and href, what will save you from otherwise unnecessary DOM alterations:

$(window).load(function(){

function downloadInnerHtml(filename, elId, mimeType, link) {
    var elHtml = document.getElementById(elId).innerHTML;
    mimeType = mimeType || 'text/plain';
    link.setAttribute('download', filename);
    link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(elHtml));
}

var fileName =  'invo.html';

$('#downloadLink').click(function(){
    downloadInnerHtml(fileName, 'Invoice','text/html', this);
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Invoice">
  CONTENT GOES HERE
</div>
<a href="#" id="downloadLink">Download</a>

Upvotes: 5

Related Questions