1

I am trying to download file by clicking on download button it should open the new tab and start downloading and once the download starts it closes the tab itself basically I do not want to have any effect on the original page. Here is my current code

const downloadHandler = (file) => {

    const a = document.createElement("a");
    a.href = file;
    a.setAttribute(`download`, file);
    a.click();
  };
  • Set `target` to `_blank` on the link. If it's JavaScript-initiated, use `window.open`. – CherryDT Aug 30 '22 at 11:01
  • See this question, I think you can do it without opening a new page. https://stackoverflow.com/questions/11620698/how-to-trigger-a-file-download-when-clicking-an-html-button-or-javascript – UnnamedXAer Aug 30 '22 at 11:02

2 Answers2

1
<a href="https://yourlink.com" target="_blank" download>fileName</a>

This will open the HTML file in a new tab

0

I recommend using the download attribute for download instead of jQuery:

<a href="your_link" download> file_name </a>

This will download your file, without opening it.

sedhal
  • 522
  • 4
  • 13
  • hi @sedhal , thanks for the kind feedback but can you please look at my description ,I updated it – Saad Nasim Ullah Aug 30 '22 at 11:11
  • Why you will be open new tab for download file because you can do in same tab without page reload. – sedhal Aug 30 '22 at 11:25
  • well the api provided by the BE developer is not letting me download file in same page , it opens the file in browser however if we could force it to download the file instead of opening it would also work – Saad Nasim Ullah Aug 30 '22 at 11:29
  • Please check this example work for you > https://codepen.io/lolfail/pen/eXLpJd – sedhal Aug 30 '22 at 11:52