Home > Web Front-end > JS Tutorial > body text

How Can I Reliably Download Data URL Files in JavaScript Across Different Browsers?

Susan Sarandon
Release: 2024-11-26 05:51:09
Original
854 people have browsed it

How Can I Reliably Download Data URL Files in JavaScript Across Different Browsers?

Downloading Data URL Files

JavaScript's ability to download files from data URLs is limited, especially in Chrome. This becomes an obstacle when working on projects that involve downloading files directly from the browser, such as creating a browser-based zip utility.

However, a solution exists to download data URL files in a way compatible with both Chrome and Firefox:

Creating Download Links

Instead of setting window.location, a better approach is to create a temporary element, set its download attribute to the desired file name, and set its href to the data URL. This method works across major browsers:

function downloadURI(uri, name) {
  var link = document.createElement("a");
  link.download = name;
  link.href = uri;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  delete link;
}
Copy after login

Example Usage:

To download a text file named "helloWorld.txt" with the content "HelloWorld!", use the following code:

downloadURI("data:text/html,HelloWorld!", "helloWorld.txt");
Copy after login

This workaround provides a reliable method for downloading data URL files, regardless of the file format or browser compatibility.

The above is the detailed content of How Can I Reliably Download Data URL Files in JavaScript Across Different Browsers?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template