amitmerchant1990 / amitmerchant-dot-com-comments

1 stars 0 forks source link

create-and-download-text-files-using-javascript/ #81

Open utterances-bot opened 1 year ago

utterances-bot commented 1 year ago

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/

blindman67 commented 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???

RinkAttendant6 commented 1 year ago

@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.

iktash commented 1 year ago

Looks like a nice little trick. However the code example still needs some polishing:

amitmerchant1990 commented 1 year ago

@iktash Good catch! I've fixed the first point. I'll check for the second one and will update it.

amitmerchant1990 commented 1 year ago

@blindman67 will this work in every modern browser?

blindman67 commented 1 year ago

@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