【问题标题】:Download <div> content as html on firefox在 Firefox 上将 <div> 内容下载为 html
【发布时间】:2018-05-21 11:46:19
【问题描述】:

我有一个 javascript,可以在点击时将 &lt;div&gt; 的内容保存为 html,它在 chrome 上运行良好,但在 firefox 上不行。

请帮我写一个跨浏览器的解决方案。

这是我的代码:

$(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>

【问题讨论】:

  • 它在 Firefox 上的作用是什么?有错误吗?您是否研究过您正在做的事情是否兼容?
  • 它什么都不做。该代码似乎与firefox完全不兼容。

标签: javascript html


【解决方案1】:

显然,只需将临时链接添加到文档即可解决 Firefox 中的问题;大概 Firefox 不喜欢clicking 不在“页面中”的元素:

$(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>

顺便说一句,在这种情况下,您可以重新使用原始“按钮”链接来保存下载和 href,这样可以避免不必要的 DOM 更改:

$(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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 2012-06-19
    • 2014-12-19
    相关资源
    最近更新 更多