Home >Web Front-end >JS Tutorial >How Can I Reliably Download Data URL Files Across Different Browsers?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-07 03:39:11712browse

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

Downloading Data URL Files

As you explore the intricacies of developing a browser-based zip/unzip utility, you encounter a challenge in downloading the processed files. While using the 'data:' scheme works in Firefox, it faces compatibility issues in Chrome. To address this, here's an alternative solution that works across multiple browsers:

The 'downloadURI' function provides a consistent way to download data URL files in Chrome, Firefox, and some versions of Internet Explorer. It dynamically creates a download link in the DOM, sets the desired file name using the 'download' attribute, and initiates the download process. After completion, the link is removed to ensure proper cleanup.

Usage:

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;
}

Example:

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

By implementing this solution, you can provide a robust and cross-browser mechanism for downloading files from data URLs. This will allow users to easily retrieve the extracted files from your zip/unzip utility within their browsers.

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

Statement:
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