function formatCSV(data) { return data.reduce( (csv, lineCells) => { let line = lineCells.reduce( (lineText, cell, idx) => { cell = '"' + cell.trim().replace(/"/g, '""') + '"'; return lineText + cell + (idx == lineCells.length - 1 ? "" : ",") }, ""); return csv + line + "\n"; }, "" ); } function saveFile(data, mimeType, fileName) { fileName = fileName || document.title || "result"; var blob; if (typeof window.Blob == "function") { blob = new Blob([data], { type: mimeType }) } else { var BlobBuiler = window.BlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder; var builer = new BlobBuiler(); builer.append(data); blob = builer.getBlob(mimeType) } var URL = window.URL || window.webkitURL; var url = URL.createObjectURL(blob); var link = document.createElement("a"); if ('download' in link) { link.style.visibility = "hidden"; link.href = url; link.download = fileName; document.body.appendChild(link); var j = document.createEvent("MouseEvents"); j.initEvent("click", true, true); link.dispatchEvent(j); document.body.removeChild(link) } else if (navigator.msSaveBlob) { navigator.msSaveBlob(blob, fileName) } else { location.href = url } } function saveFileAsk(data) { let csv = formatCSV(data.slice(1, 50)).trim() || "- Empty -"; if (confirm(`Click confirm to download if the sample data looks good (${data.length-1} items):\n\n${csv}`)) { csv = formatCSV(data); saveFile(csv, "text/csv"); } }