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; }
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");
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!