61

I have an odd problem, the function below is one I created based on what i found on the net about creating a Blob in the client on the fly with some binary data in (passed as an array) and being able to download that. This works brilliantly in Chrome, but doesn't do anything in Firefox - UNLESS I debug and step through the code. Yes, oddly, if I create a break point inside the function and step through it, the a.click() will bring up the download window!

function downloadFile(filename, data) {

    var a = document.createElement('a');
    a.style = "display: none";  
    var blob = new Blob(data, {type: "application/octet-stream"});
    var url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);    
}

Can anyone help me? This was tested using Firefox 38.0.5.

Johncl
  • 1,211
  • 1
  • 12
  • 13

3 Answers3

91

You're probably removing the resource too soon, try delaying it

    ...
    a.click();
    setTimeout(function(){
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);  
    }, 100);  
}
Musa
  • 96,336
  • 17
  • 118
  • 137
  • Had a similar problem with a Blob Object URL created in a Worker that got implicitly revoked after closing the Worker. Your answer got me on the right track, adding a timeout before closing the Worker fixed it.. thanks! – meyertee Nov 03 '15 at 22:39
  • 4
    Just wanted to note that delay `0` works just as well from what I can tell - Firefox just needs a hint that whatever you're doing can go to the end of the call stack, the actual duration appears to be irrelevant. – jrz May 28 '16 at 15:59
  • Oddly enough, that wasn't the problem with me, but I had to add a delay before appending the anchor into the document, nevertheless, got it to work mainly with your idea. – downhand Jul 26 '16 at 06:47
12

The above didn't solve the issue for me. But this one did instead:
Programmatical click on <a>-tag not working in Firefox
It was a problem with the triggering click event, not premature removal of the resource.

Tomek
  • 502
  • 6
  • 14
4

this solution works for me in bot chrome and firefox for existing anchor element to download binary file

window.URL = window.URL || window.webkitURL;

var blob = new Blob([new Uint8Array(binStream)], {type: "octet/stream"});

var link = document.getElementById("link");
link.href = window.URL.createObjectURL(blob);
Azad
  • 5,144
  • 4
  • 28
  • 56
  • I used your example, it works: var link = document.getElementById("link"); link.href = window.URL.createObjectURL(response); link.download = filename; link.click(); – ticky Nov 15 '18 at 14:39