Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initiating a download with javascript

Tags:

I need to dynamically initiate a download with javascript. I have seen how people do this by doing something like

window.open("some url", "Download"); 

but I need to do it without changing the url of the current page (and not using frames if I can help it, or created and destroying a frame dynamically). Anybody know how to do this?

like image 524
kzip Avatar asked Sep 05 '10 03:09

kzip


People also ask

How do I trigger a download when clicking HTML button or JavaScript?

To trigger a file download on a button click we will use a custom function or HTML 5 download attribute. The download attribute simply uses an anchor tag to prepare the location of the file that needs to be downloaded.

Can JavaScript create a file?

Did you know you can create files using JavaScript right inside your browser and have users download them? You can create files with a proper name and mime type and it only takes a few lines of code.


1 Answers

You don't need window.open(). It's plain ugly and prone to popupblockers (where you have no control over in clients). Just window.location is sufficient if the response header of the requested download URL contains Content-Disposition: attachment. This won't change the current URL in the browser address bar nor the current page, but just pop a Save As dialogue.

E.g.

window.location = 'http://download.winzip.com/winzip145.exe'; 
like image 68
BalusC Avatar answered Sep 24 '22 04:09

BalusC