简体   繁体   English

<a>标记上的</a>下载属性<a>在Chrome中不起作用</a>

[英]download attribute on <a> tag doesn't work in Chrome

As I click the export button, chrome will download a file called "download" whose type is "Document". 当我单击导出按钮时,chrome将下载名为“download”的文件,其类型为“Document”。 If I add the extension(.xls) manually, the content of the downloaded file is correct. 如果我手动添加扩展名(.xls),则下载文件的内容是正确的。 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. 此外,在我尝试了不同的PC之后,其中一些可以下载具有正确名称的文件,其中一些与我的相同。 And this code is not working for Firefox in all machines. 并且此代码在所有计算机中都不适用于Firefox。

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. 这应该有效(我以前使用了与页面内生成的文件基本相同的代码,并且它已经有效),但目前在最新版本的Chrome上存在一个未解决的问题( https://code.google.com/p关于“下载”属性被忽略的/ chromium / issues / detail?id = 366370 )。 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根据W3C推荐故意忽略了跨源链接的下载属性(在我看来这是一个愚蠢的推荐,但它仍然是一个推荐)。 Chrome might be treating "data:" URLs as cross-origin and thus ignoring your download attribute; Chrome可能会将“data:”网址视为交叉来源,从而忽略了您的下载属性; 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 编辑:看起来还有另一个当前错误解决数据URI的问题: https//code.google.com/p/chromium/issues/detail? id = 373182

So, yeah, your code is correct; 所以,是的,你的代码是正确的; this is a bug in Chrome. 这是Chrome中的一个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM