如何在所有浏览器上从 javascript 变量下载文本?

How to download text from javascript variable on all browsers?

我需要一个函数来将 javascript 变量中的字符串下载到文本文件 (5-7MB) 中。该功能应该跨浏览器工作。

我试过制作这样的下载功能,但它在 Chrome 上不起作用。 FireFox 打开 'save' 对话框,但 Chrome 不会。此外,当我在 Chrome 中禁用 'ask where to save file' 时,它显示 'Failed - Network Error'。由于我都是在本地做所有事情,所以我不明白为什么会出现这个问题。

function download(filename, text) {
 var element = document.createElement('a');
 element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
 element.setAttribute('download', filename);

 element.style.display = 'none';
 document.body.appendChild(element);

 element.click();

 document.body.removeChild(element);

}

这不会打开任何用于在 Chrome(版本 76.0.3809.132)上保存文件的对话框。 Microsoft Edge (44.17763.1.0) 也有同样的问题。我希望它适用于所有浏览器,或者至少适用于 FireFox 和 Chrome.

编辑 1: Chrome 问题似乎在其他计算机上仍然存在,因此浏览器不会有问题。我也宁愿做自己的功能而不是使用其他项目(公司问题)。

编辑 2: Chrome 中锚点大小似乎限制为 2MB。有解决方法吗?有一些建议使用 BLOB 的答案,但我不熟悉这个概念。任何解释将不胜感激。

如果这个图标出现在您的地址栏中

然后检查您的 Chrome 配置 to enable automatic downloads

我发现了一个简单的修改,现在可以在我的 FireFox 和 Chrome 上运行。它使用 BLOB 来绕过锚点大小限制。不过它仍然不适用于 Microsoft Edge。

function download(filename, text, type="text/plain") {
  // Create an invisible A element
  const a = document.createElement("a");
  a.style.display = "none";
  document.body.appendChild(a);

  // Set the HREF to a Blob representation of the data to be downloaded
  a.href = window.URL.createObjectURL(
    new Blob([text], { type })
  );

  // Use download attribute to set set desired file name
  a.setAttribute("download", filename);

  // Trigger the download by simulating click
  a.click();

  // Cleanup
  window.URL.revokeObjectURL(a.href);
  document.body.removeChild(a);
}