javascript Anchor 的下载属性在某些页面 (Gmail) 上不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13912198/
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
Anchor's Download Property is not working on some pages (Gmail)?
提问by Ashraf Bashir
I want to insert this HTML element in some pages:
我想在某些页面中插入这个 HTML 元素:
<a download="somedata.csv"
id="downloadLink"
href="data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333"
>
Click Me
</a>
In all pages, when I change the dom via plugin or manually in elements inspector, to include this element to page's dom, it works great !
But, if I do the same in Gmail pages, the file generated is not named "somedata.csv
" and the extension is lost "csv
" !
在所有页面中,当我通过插件或在元素检查器中手动更改 dom 时,将此元素包含到页面的 dom 中时,效果很好!
但是,如果我在 Gmail 页面中执行相同操作,生成的文件不会命名为“ somedata.csv
”,并且扩展名会丢失“ csv
”!
I tried this in local file, in file uploaded to localhost, and in many external website pages, it works in all except for Gmail pages.
我在本地文件、上传到本地主机的文件和许多外部网站页面中尝试了这个,它适用于除 Gmail 页面之外的所有页面。
Why it doesn't work in Gmail pages ? And how to fix this ?
为什么它在 Gmail 页面中不起作用?以及如何解决这个问题?
采纳答案by Ashraf Bashir
For those who are interested, I solved it using Javascript/Ajax, here's the solution:
对于那些有兴趣的人,我使用 Javascript/Ajax 解决了它,这是解决方案:
Here's the function:
这是函数:
var downloadDataURI = function($, options) {
if(!options)
return;
$.isPlainObject(options) || (options = {data: options});
if(!$.browser.webkit)
window.location = options.data;
options.filename || (options.filename = "download." + options.data.split(",")[0].split(";")[0].substring(5).split("/")[1]);
options.url || (options.url = "http://download-data-uri.appspot.com/");
$('<form method="post" action="'+options.url+'" style="display:none"><input type="hidden" name="filename" value="'+options.filename+'"/><input type="hidden" name="data" value="'+options.data+'"/></form>').submit().remove();
}
And here's how to call it:
这是如何调用它:
downloadDataURI($, {filename: "test.csv",data:"data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333"});
回答by Wilfred
In Chrome with JQuery, I try this approach:
在带有 JQuery 的 Chrome 中,我尝试了这种方法:
var dataUri = "data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333"
var filename = "somedata.csv"
$("<a download='" + filename + "' href='" + dataUri + "'></a>")[0].click();
I created a temp link and trigger click event on it. but not sure if other browsers work or not.
我创建了一个临时链接并在其上触发点击事件。但不确定其他浏览器是否有效。