4

The download attribute of an <a> tag helps Edge open download links more nicely (i.e. it closes the target tab once it realises it won't be used). Is there any way to do that when Javascript is responsible for initiating the download? As in

HTML:

<span class='btn-link' onclick='openReport(@orderNumber, @tableBodyId); return false;'>

Javascript (talking to ASP.NET MVC controller):

function openReport(orderNumber, tableBodyId) {
    var url = "/Reports/ValuationReportDocPdf?orderNumber=" + orderNumber;
    var win = window.open(url, '');
    setTimeout(function () { location.reload(); }, 3000);
}
Community
  • 1
  • 1
OutstandingBill
  • 2,614
  • 26
  • 38
  • 1
    Maybe this will work for you: http://stackoverflow.com/questions/25087009/trigger-a-file-download-on-click-of-button-javascript-with-contents-from-dom/25087107#25087107 – chrki Feb 26 '17 at 12:30
  • 1
    @chrki - yes, that does the trick for me, thank you! Please submit as an answer, and I'll accept. I also had to detect Edge (because the suggested method didn't work in FF/Chrome), using [this](http://stackoverflow.com/questions/42002903/how-to-prevent-a-blank-tab-from-appearing-in-edge-when-clicking-on-a-file-link) – OutstandingBill Feb 27 '17 at 03:50

1 Answers1

2

I'm not aware of any Javascript function or setting that lets you change the filename when downloading, or any that imitates the download attribute on <a> tags.

In a similar question, this answer by user3758133 outlines a workaround where you programmatically create a link, attach the proper download attribute and trigger a click:

("#downloadbutton").click(function() {
  //var content = content of file;
  var dl = document.createElement('a');
  dl.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(content));
  dl.setAttribute('download', 'filename.txt');
  dl.click();
});
Community
  • 1
  • 1
chrki
  • 6,143
  • 6
  • 35
  • 55
  • Thanks! In case anyone's interested, [here are some further details](http://stackoverflow.com/questions/42356146/open-a-pdf-from-edge-without-opening-redundant-blank-tabs/42477576#42477576) on how I implemented this. – OutstandingBill Mar 01 '17 at 01:03