1

I’m trying to use this trick to open a file download dialog on document ready. The same trick has worked another time for me, but that time the iframe was added after an ajax call. This is the snippet:

<script type="text/javascript">
  $(document).ready(function() {
     var url='/my_file_url/';
     var _iframe_dl = $('<iframe />')
                       .attr('src', url)
                       .hide()
                       .appendTo('body');
  });
</script>

While the iframe is correctly printed in html code, it doesn’t have the expected behaviour: no download file popup appears after loading the page. Any help on why?

franzlorenzon
  • 5,845
  • 6
  • 36
  • 58
Luke
  • 1,794
  • 10
  • 43
  • 70

1 Answers1

4

It works just fine, assuming that the MIME is of a type that will start a download, for example application/octet-stream. You may be encountering an issue where the browser is rendering it and not offering a download due to an in-built pdf reader.

$(document).ready(function(){
var url='data:application/octet-stream,hello%20world';
var _iframe_dl = $('<iframe />')
       .attr('src', url)
       .hide()
       .appendTo('body');
});

An alternate solution, if the client is on a modern browser, is to use an <a> with href and download set, then simulate a click on it.

var a = document.createElement('a'),
    ev = document.createEvent("MouseEvents");
a.href = url;
a.download = url.slice(url.lastIndexOf('/')+1);
ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0,
                  false, false, false, false, 0, null);
a.dispatchEvent(ev);
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • thnks paul but i still didnt uderstand where is my mistake: http://jsfiddle.net/MjuQP/ – Luke Apr 22 '13 at 10:42
  • That fiddle doesn't have jquery added, nor does it include the JavaScript at the right time (see settings on left). Further, the issue seems to come from the `.pdf` file ext – Paul S. Apr 22 '13 at 10:49
  • 1
    Modernest browsers (e.g. Chrome) can do `a.click()` in stead of the `ev` stuff. – Redsandro Feb 06 '14 at 02:18
  • @Redsandro `element.click` has been in [**the spec**](http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-2651361) since _2003_ or earlier, there is nothing _modern_ about it; the point of dispatching an event in this code is to simulate a mouse click as close as possible to as if it really happened. – Paul S. Feb 06 '14 at 03:08
  • __@Paul S:__ Where did I say that `element.click` has been in the spec only recently? You could only do `element.click` on an `element` that is in the `DOM`. Your example doesn't have `a` in the `DOM`, so you need a modern browser like Chrome to do `element.click` on it, because the past 10 years it wouldn't work like that. – Redsandro Feb 06 '14 at 13:14