Home >Web Front-end >JS Tutorial >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; }
Usage
To use this function, provide the data URL and the desired download filename as arguments:
downloadURI("data:text/html,HelloWorld!", "helloWorld.txt");
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!