OutstandingBill
OutstandingBill

Reputation: 2844

Any way to mimic the download attribute of an anchor tag?

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);
}

Upvotes: 4

Views: 2970

Answers (1)

chrki
chrki

Reputation: 6323

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();
});

Upvotes: 2

Related Questions