我如何在FF和Chrome中使用链接下载属性

How do I use link download attribute in FF and Chrome?

本文关键字:链接 下载 属性 Chrome FF      更新时间:2023-09-26

经过我在这里和其他网站上的所有研究,我已经到达以下代码用于保存一些给定的文本("文本"变量)与给定的文件名("fileName"变量),但它只在IE中完美地工作。Firefox下载该文件,但使用自己的随机名称(如"G5QJNAr0")。Chrome什么也不做。

try {
    var blob = new Blob([text], {
         type: "text/csv;charset=utf-8"
    });
    if (window.navigator.msSaveOrOpenBlob) {
         window.navigator.msSaveBlob(blob, fileName);
    } else {
        var encodedData = encodeURI(text);
        var link = document.createElement("link");
        link.setAttribute("download", fileName);
        if ( 'URL' in window ) {
            link.setAttribute("href", window.URL.createObjectURL(blob));
            link.setAttribute("target", "_blank");
            link.style.display = "none";
            document.body.appendChild(link);
        } else if ( 'webkitURL' in window ) {
            link.setAttribute("href", window.webkitURL.createObjectURL(blob));
        }
        link.click();
    }
} catch (e) {
    alert("Got error trying download text: " + e);
}

没有浏览器提示异常。

Chrome通过我设置的所有断点并单击最后的链接。但是什么也没做。

有人能帮助我的文件名和无响应问题在FF和Chrome分别?

remove

link.setAttribute("target", "_blank");

改变
var link = document.createElement("link");

var link = document.createElement("a");

两个浏览器的细微差别是在锚"a"内部创建了一个"链接"。

var link = document.createElement("a");