0

Possible Duplicate:
Force download through js or query

I'm trying to write javascript which, when given a url, tells the user's browser to download the resource pointed to be the url. What I want is basically:

function download(url) { ... }

I can get the window to be set using window.open(url), but the problem is that the browser still gets to decide whether to display or download the file. Since I don't, from the javascript, have control over the MIME type, I need a way to, using javascript, instruct the browser to ignore the MIME type and download the resource. Basically the same thing that happens when you right-click a link and click "download" or the equivalent.

Side note: I've tried using the html5 tag's "download" attribute, and at least one browser (firefox) doesn't properly implement it at the moment, so that's off the table for now.

Community
  • 1
  • 1
joshlf
  • 21,822
  • 11
  • 69
  • 96

2 Answers2

0

You can't do this. It will open too many possibilities for malware since it will enable the JS to download files on the computer without any user interaction. What you can do is to make a PHP script, and proxy all requests to resources you want the browser to download trough this PHP, and the PHP will send the appropriate HTTP headers to force download.

Maxim Krizhanovsky
  • 26,265
  • 5
  • 59
  • 89
  • It would not be a security threat. Even if the javascript decides to download a file, the user still has to decide where the page goes (and if it goes somewhere). – John Dvorak Dec 19 '12 at 08:07
0

I think this might help:

Put this JavaScript code in the body of your HTML:

<A HREF="javascript:popUp('http://yoururl.com')</a>
John Dvorak
  • 26,799
  • 13
  • 69
  • 83
Arsalan
  • 72
  • 9