Open utterances-bot opened 1 year ago
The following is an update to consider
function saveTextAsFile(text, filename, type = "text/plain") {
Object.assign(document.createElement('a'), {
download: filename,
href: URL.createObjectURL(new Blob([text], { type }))
}).click();
}
webkitURL
has no support???
@blindman67 webkitURL
is the name for the URL
object that was implemented in Chromium-based browsers before January 2014: https://developer.mozilla.org/en-US/docs/Web/API/URL#browser_compatibility
It's probably safe to omit that these days and just use URL
, considering that Chromium has signalled intent to deprecate the prefixed version for many years now.
Looks like a nice little trick. However the code example still needs some polishing:
@iktash Good catch! I've fixed the first point. I'll check for the second one and will update it.
@blindman67 will this work in every modern browser?
@amitmerchant1990 It will work on all browsers apart from IE-11 and Opera-Mini. However I do not consider them modern browsers. Be warned that any download can be blocked by the client, running any download function does not guarantee a download, nor is there any method you can use to discover if the download completed or even started
Create and download text files using JavaScript — Amit Merchant — A blog on PHP, JavaScript, and more
There are a couple of projects of mine where I needed to create and download text/JSON files using JavaScript. For instance, in LinkSnatch, I needed a way to export the bookmarks as a JSON file or in my Notepad app, I needed a way to export the notes as a text file.
https://www.amitmerchant.com/create-and-download-text-files-using-javascript/