0

I am trying to download csv file form html table.

<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<html>
<body>

<table>
<tr>
    <th>Name</th>
    <th>Email</th>
    <th>Country</th>
</tr>
<tr>
    <td>John Doe</td>
    <td>john@gmail.com</td>
    <td>USA</td>
</tr>
<tr>
    <td>Stephen Thomas</td>
    <td>stephen@gmail.com</td>
    <td>UK</td>
</tr>
<tr>
    <td>Natly Oath</td>
    <td>natly@gmail.com</td>
    <td>France</td>
</tr>
</table>
<button onclick="exportTableToCSV('members.csv')">Export HTML Table To CSV File</button>

 <script>
function downloadCSV(csv, filename) {
var csvFile;
var downloadLink;

// CSV file
csvFile = new Blob([csv], {type: "text/csv"});

// Download link
downloadLink = document.createElement("a");

// File name
downloadLink.download = filename;

// Create a link to the file
downloadLink.href = window.URL.createObjectURL(csvFile);

// Hide download link
downloadLink.style.display = "none";

// Add the link to DOM
document.body.appendChild(downloadLink);

// Click download link
downloadLink.click();// throwing error.

}
function exportTableToCSV(filename) {
var csv = [];
var rows = document.querySelectorAll("table tr");

for (var i = 0; i < rows.length; i++) {
    var row = [], cols = rows[i].querySelectorAll("td, th");

    for (var j = 0; j < cols.length; j++) 
        row.push(cols[j].innerText);

    csv.push(row.join(","));        
}

// Download CSV file
downloadCSV(csv.join("\n"), filename);
}

</script>

</body>
</html>

But on IE 11 getting error as SCRIPT5: Access is denied. at downloadLink.click();

Same code working as expected in other browser like chrome, mozilla firefox etc. any help is much appreciated.

code ref: https://www.codexworld.com/export-html-table-data-to-csv-using-javascript/?

softDev
  • 1
  • 1
  • 2
  • Maybe use `.addEventListener()` instead of `onclick` attribute? It's a suggestion, not a sure solution, but sometimes browsers block code from prompting downloads unless it's invoked directly by a user event. In this case invoking something in the `onclick` attribute may not count as being triggered by a user event to IE11 – Patrick Roberts Apr 17 '18 at 08:46
  • Possible duplicate of [Download attribute on A tag not working in IE](https://stackoverflow.com/questions/18394871/download-attribute-on-a-tag-not-working-in-ie) – Asons Apr 17 '18 at 09:01
  • Possible duplicate of [IE 10: SCRIPT5: Access is Denied error on anchor click event](https://stackoverflow.com/questions/21988774/ie-10-script5-access-is-denied-error-on-anchor-click-event) – Ravi Ranjan Apr 17 '18 at 09:06

0 Answers0