问题
As I click the export button, chrome will download a file called "download" whose type is "Document". If I add the extension(.xls) manually, the content of the downloaded file is correct. I wonder how does the download attribute work in such a situation. Here is my code:
a = document.createElement("a");
var data_type = 'data:application/vnd.ms-excel,';
var table_div = document.getElementById('table');
var table_html = table_div.outerHTML.replace(/ /g, '%20');
a.download = "excel.xls";
a.href = data_type + table_html;
a.click();
Moreover, after I tried different PCs, some of them can download the file with the proper name, some are same with mine. And this code is not working for Firefox in all machines.
回答1:
This should work (I have used essentially identical code for in-page-generated files before, and it has worked), but there is currently an open issue on the latest version of Chrome (https://code.google.com/p/chromium/issues/detail?id=366370) concerning the "download" attribute being ignored. It seems that the latest versions of Chrome intentionally ignore the download attribute on cross-origin links according to W3C recommendation (a stupid recommendation in my opinion, but it is a recommendation nonetheless). Chrome might be treating "data:" URLs as cross-origin and thus ignoring your download attribute; if so, there's pretty much nothing you can do about it.
Edit: Looks like there is another current bug addressing data URIs specifically: https://code.google.com/p/chromium/issues/detail?id=373182
So, yeah, your code is correct; this is a bug in Chrome.
来源:https://stackoverflow.com/questions/23962284/download-attribute-on-a-tag-doesnt-work-in-chrome