Ian Marshall logo

Ian Marshall

Q: This is crazy but I don't know how to do this, and because of how common the words are, it's hard to find what I need on search engines. I'm thinking this should be an easy one to answer: I want a simple file download triggered via JavaScript. I'm definitely *not* looking for a way to create an anchor that looks like a button, use any back-end scripts, or mess with server headers or mime types.

How to trigger a file download with JavaScript when clicking an HTML button?

Not crazy! I did exactly the same thing when I wanted users to be able to download images created on an HTML canvas:


No doubt you could use the same approach. Create an anchor element (you don't even have to attach it to the DOM), set the name of the downloading file (optional), set the href attribute, then trigger its click() method.

I do a lot of work with canvas, and I use this exact function in many places. It works!

I hope this helps! Let me know if you need more help on this subject.