On click of a button, CSV file should get downloaded. I have used below Javascript code for same. JS:
functionName(){
var anchorTag = document.createElement('a');
anchorTag.href="data:text/csv;charset=utf-8," + encodeURI(csvStringResult); //csv processed data
anchorTag.target="_self";
anchorTag.download="file name.csv";
anchorTag.innerHTML = "link text";
document.body.appendChild(anchorTag);
anchorTag.click();
}
HTML:
<lightning-button variant="destructive" icon-name="utility:download" label="Download" class="slds-m-left_x-small" title="Download"
onclick={functionName}></lightning-button>
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?