3

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.

Yongyiw
  • 248
  • 1
  • 4
  • 8
  • The document downloading should be managed server side. You should call a controller function or a php file and manage header from that place. – sdespont May 30 '14 at 19:43
  • Thanks @sdespont, but I wonder if I can generate the excel file directly from the page, because all the data have already displayed on the page. Is that a proper way to do that? – Yongyiw May 30 '14 at 23:05
  • Pretty sure that the 'download' attribute is specific to Chrome - FF and IE will not respect it. – Stephen Jun 01 '14 at 05:07
  • Off Topic: I think you should use `encodeURIComponent(table_div.outerHTML)`, so you can be sure that everything that needs to be encoded is really encoded. Alternatively you could create a blob and blob URL (might be better for large files). – panzi Jul 19 '14 at 17:28

1 Answers1

3

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.

Logan R. Kearsley
  • 682
  • 1
  • 5
  • 19
  • Thank you so much! @Logan R. Kearsley That's exactly what I suspect. So I will find other way to do that – Yongyiw Jun 04 '14 at 21:33
  • This issue may be caused by [a security feature](https://html.spec.whatwg.org/multipage/links.html#downloading-resources) of the HTML Standard. There's a workaround using Blob [on a similar issue reported in Chromium](https://bugs.chromium.org/p/chromium/issues/detail?id=373182#c69). – dlauzon Jun 22 '22 at 19:10