On click of a button, CSV file should get downloaded. I have used below Javascript code for same. JS:

var anchorTag = document.createElement('a');
anchorTag.href="data:text/csv;charset=utf-8," + encodeURI(csvStringResult); //csv processed data
anchorTag.download="file name.csv";
anchorTag.innerHTML = "link text";


<lightning-button variant="destructive" icon-name="utility:download" label="Download" class="slds-m-left_x-small" title="Download"

But when I click the button for 1st time, the page gets reloaded. When I click the button for the second time, the file gets downloaded and the page is not reloaded.

I tried setting anchorTag.href="test.com";. Blank file gets downloaded but still page is reloaded. When I comment anchorTag.download="file name.csv"; in this case page is not reloaded.

There are 3 buttons on the page doing the same function.

How should I prevent it from reloading for 1st time while downloading the file?


Though the same code works for me https://www.salesforcecodecrack.com/2019/05/export-data-as-csv-file-with-javascript.html , but it depends on your template.

Try to add attribute as type="button", defaults to button which will tell the browser that its a button and don't treat it as a form.

Or else try to return false at the end of the function.

May be you might be having this inside a form and the button might be acting as a submit action.

  • I tried adding anchorTag.type="button";. but still the same issue. Also, I have not used the form. – Ajinkyasd Nov 19 '20 at 8:08
  • did you try returning false, or try event.stopImmediatePropagation(); also can you paste the full html code, so as to replicate the issue , as its not replicable in my org. – Nagendra Singh Nov 19 '20 at 8:12
  • @Ajinkyasd Nagendra is correct. you should start your function off as functionName(event) { event.preventDefault(); then create the link. There's no need to add it to the body, either, the browser should automatically download the file when you click() the anchor tag. – sfdcfox Nov 19 '20 at 8:41
  • @sfdcfox/nagendra I tried both the solutions but didnt work. still page gets reloaded. code: functionName(event){ //above code.. in description //event.stopImmediatePropagation(); event.preventDefault(); } – Ajinkyasd Nov 19 '20 at 9:15
  • That's odd, can you try to do the same thing in playground developer.salesforce.com/docs/component-library/tools/…, and pass the playground link if its replicable. – Nagendra Singh Nov 19 '20 at 9:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.