Home > Web Front-end > JS Tutorial > How to Download Data URLs in JavaScript: A Chrome and Firefox Solution?

How to Download Data URLs in JavaScript: A Chrome and Firefox Solution?

Barbara Streisand
Release: 2024-11-27 02:54:14
Original
721 people have browsed it

How to Download Data URLs in JavaScript: A Chrome and Firefox Solution?

Downloading Data URLs in JavaScript

In an attempt to create a JavaScript-based zip/unzip utility, you've encountered an issue with downloading files encoded in data URLs. While this approach works in Firefox, it fails in Chrome.

Chrome's Dilemma

Chrome does not support directly downloading data URLs. Instead, it embeds them as images when referenced using img tags. This poses a problem for non-image file formats.

A Workaround

Fortunately, a workaround exists to enable data URL downloads in both Chrome and Firefox. The solution involves creating a temporary a element, setting its download attribute to the desired filename, and assigning the data URL to its href attribute.

Code Example

The following JavaScript function, downloadURI, implements this workaround:

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

Usage

To use this function, provide the data URL and the desired download filename as arguments:

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

This approach will prompt a download dialog in both Chrome and Firefox, allowing users to save the file with the specified filename.

The above is the detailed content of How to Download Data URLs in JavaScript: A Chrome and Firefox Solution?. 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