JSFiddle - React, Tailwind, and code Playground
by Loreto Parisi
HTML
<script>
/**
* Save a text as file using HTML <a> temporary element and Blob
* @see https://stackoverflow.com/questions/49988202/macos-webview-download-a-html5-blob-file
* @param fileName String
* @param fileContents String JSON String
* @author Loreto Parisi
*/
var saveBlobAsFile = function(fileName, fileContents) {
if (typeof(Blob) != 'undefined') { // using Blob
var textFileAsBlob = new Blob([fileContents], {
type: 'text/plain'
});
var url;
var downloadLink = document.createElement("a");
downloadLink.download = fileName;
if (window.webkitURL != null) {
url = window.webkitURL.createObjectURL(textFileAsBlob);
downloadLink.href = url
console.log(downloadLink.href)
} else {
url = window.URL.createObjectURL(textFileAsBlob);
downloadLink.href = url
//downloadLink.onclick = document.body.removeChild(event.target);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
window.URL.revokeObjectURL(url);
} else {
var pp = document.createElement('a');
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
pp.setAttribute('download', fileName);
pp.onclick = document.body.removeChild(event.target);
pp.click();
}
} //saveBlobAsFile
function download() {
console.log("download");
var jsonObject = {
"name": "John",
"age": 31,
"city": "New York"
};
var fileContents = JSON.stringify(jsonObject, null, 2);
var fileName = "data.json";
saveBlobAsFile(fileName, fileContents);
return false;
}
</script>
<button id="download" onclick="download()">Download...