ajith kumar
ajith kumar

Reputation: 361

Download file without refreshing the page

I have a javascript page it has a table that has certain details. on click of a row, it will download a JSON file. I am able to download the file but the page refreshes after the download.

function testDownload() {
  const data = { a: "ajith", b: "kumar" };
  const dataStr =
    "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(data));
  const downloadAnchorNode = document.createElement("a");
  downloadAnchorNode.setAttribute("href", dataStr);
  debugger;
  downloadAnchorNode.setAttribute("id", "anchor");
  downloadAnchorNode.setAttribute("download", "extracted" + ".json");
  document.body.appendChild(downloadAnchorNode); // required for firefox
  downloadAnchorNode.click();
}

How to restrict the page refresh after the download has completed?

Upvotes: 1

Views: 3412

Answers (2)

hrdom
hrdom

Reputation: 168

My situation is that the page will jump/change to another site.
In my case, it needs to be changed like this:

function testDownload() {
  const data = { a: "ajith", b: "kumar" };
  const dataStr =
    "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(data));
  const downloadAnchorNode = document.createElement("a");
  downloadAnchorNode.setAttribute("href", dataStr);
  debugger;
  downloadAnchorNode.setAttribute("id", "anchor");
  downloadAnchorNode.setAttribute("download", "extracted" + ".json");
  document.body.appendChild(downloadAnchorNode); // required for firefox

  downloadAnchorNode.onclick = (e) => { // Add this
      e.stopPropagation();
  }

  downloadAnchorNode.click();
}

My reason is probably that the click event bubbled up on two ancestor elements, <body> or <document>. Triggers event listener bound to one of its two elements.

Upvotes: 0

Saeed Jamali
Saeed Jamali

Reputation: 1195

If you click on a button to download the JSON, try this code:

function testDownload(e) {
  e.preventDefault();
  const data = { a: "ajith", b: "kumar" };
  const dataStr =
    "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(data));
  const downloadAnchorNode = document.createElement("a");
  downloadAnchorNode.setAttribute("href", dataStr);
  debugger;
  downloadAnchorNode.setAttribute("id", "anchor");
  downloadAnchorNode.setAttribute("onclick", "testDownloadFun(event)");
  downloadAnchorNode.setAttribute("download", "extracted" + ".json");
  document.body.appendChild(downloadAnchorNode); // required for firefox
  downloadAnchorNode.click();
}

I added the "preventDefault" method.

Upvotes: 1

Related Questions