Javascript 下载属性在 Firefox 中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27115748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Download attribute not working in Firefox
提问by MattSidor
I'm trying to let the user download some data as a CSV (text) file, using Javascript and the HTML5 Download attribute (http://caniuse.com/#feat=download).
我试图让用户使用 Javascript 和 HTML5 下载属性 ( http://caniuse.com/#feat=download)将一些数据下载为 CSV(文本)文件。
The data is formed in an array, and then added to a new Blob object.
数据形成一个数组,然后添加到一个新的 Blob 对象中。
It works perfectly in Chrome and Opera, but does not work at all in Firefox.
它在 Chrome 和 Opera 中完美运行,但在 Firefox 中根本不起作用。
Original example I am attempting to copy: http://blog.eliacontini.info/post/79860720828/export-to-csv-using-javascript-the-download-attribute
我试图复制的原始示例:http: //blog.eliacontini.info/post/79860720828/export-to-csv-using-javascript-the-download-attribute
Fiddle: http://jsfiddle.net/8wos7cf8/5/
小提琴:http: //jsfiddle.net/8wos7cf8/5/
Javascript:
Javascript:
$('#downloadButton').click(function () {
// some data to export
var data = [{
"title": "Book title 1",
"author": "Name1 Surname1"
}, {
"title": "Book title 2",
"author": "Name2 Surname2"
}, {
"title": "Book title 3",
"author": "Name3 Surname3"
}, {
"title": "Book title 4",
"author": "Name4 Surname4"
}];
// prepare CSV data
var csvData = new Array();
csvData.push('"Book title","Author"');
data.forEach(function (item, index, array) {
csvData.push('"' + item.title + '","' + item.author + '"');
});
// download stuff
var fileName = "data.csv";
var buffer = csvData.join("\n");
var blob = new Blob([buffer], {
"type": "text/csv;charset=utf8;"
});
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
link.setAttribute("href", window.URL.createObjectURL(blob));
link.setAttribute("download", fileName);
link.click();
} else {
alert('CSV export only works in Chrome, Firefox, and Opera.');
}
});
HTML:
HTML:
<div class="toggle-button" id="downloadButton"><span>Export to CSV</span></div>
When I add an alert with:
当我添加警报时:
alert(window.URL.createObjectURL(blob));
I get this result in Firefox:
我在 Firefox 中得到这个结果:


...and this result in Chrome/Opera:
...这在 Chrome/Opera 中的结果:


So it seems like it omits the URL path in Firefox for some reason.
因此,它似乎出于某种原因省略了 Firefox 中的 URL 路径。
回答by jmfolds
You might try adding the element to the DOM before triggering the click:
您可以尝试在触发点击之前将元素添加到 DOM:
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
This worked for me in Firefox 34
这在 Firefox 34 中对我有用
jsfiddle: http://jsfiddle.net/8wos7cf8/7/
jsfiddle:http: //jsfiddle.net/8wos7cf8/7/

