Force download through js or query

Is it possible to force a download through JS or Javascript i-e the web page should not open the file in new tab in the browser but to pop up to let the user to choose eith "save as" or open with ???



You can not force that behavior from JavaScript, the HTTP Headers need to be set on the server side:


The way you can solve the problem is to let your AJAX method redirect the user to the URL of the PDF:


(The above HTTP headers must be set for the PDF)


At the time of this answer, it wasn't possible. Now it is, scroll down to see the other answer saying so.


With the advent of HTML5 you could just use the new property download in the anchor tag.

The code will look something like

<a download="name_of_downloaded_file" href="path/to/the/download/file"> Clicking on this link will force download the file</a>

It works on firefox and chrome latest version. Should I mention that I didn't check it in IE? :P

Edited the download attribute after comment from sstur


dynamic create link and click it with download attribute for force download as file:

var anchor = document.createElement('a');
anchor.href = this.props.download_url; = '_blank'; = this.props.file_name;;

Take a notice that i didn't even added it to DOM, so it's fast.

P.S download attribute won't work with IE. But it will just open link in new tab.


No this is not possible with JQuery/JavaScript only.

You will need a server side script which returns you the file with a Content-Type (HTTP Header) which will force the browser to download your requested file. An possible value for Content-Type would be application/force-download.


No, it is not possible and thanks God it isn't. Otherwise I leave you to the imagination of what kind of files could be stored on your computer when you visit a web site without you knowing it.

As @Paul D. White pointed out in the comments section if you want to open the file inline (inside the browser) with the default program associated with it you could have the server send the Content-Disposition HTTP header. For example:

Content-Disposition: inline; filename=foo.pdf


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.