代码实现的是点击导出按钮让用户可以下载 test.txt 文件:web
<textarea id="ta_text"></textarea> <button type="button" onclick="saveFile()">导出</button> <script> function exportTxt(fileName, data) { if (navigator.userAgent.indexOf("Trident") &amp;gt;= 0) { try { // IE 10 或以上 var fileObj = new Blob([data]); navigator.msSaveBlob(fileObj, fileName); } catch (ex) { // IE 9 或如下 var winSave = window.open(); winSave.document.open("text", "utf-8"); winSave.document.write(data); winSave.document.execCommand("SaveAs", true, fileName); winSave.close(); } } else { // Webkit var urlObject = window.URL || window.webkitURL || window; var export_blob = new Blob([data]); var save_link = document.createElement("a"); save_link.href = urlObject.createObjectURL(export_blob); save_link.download = fileName; save_link.click(); } } function saveFile() { var text = document.querySelector("#ta_text").value; exportTxt("test.txt", text); } </script>
webkit 内核的浏览器会将一个连接到 blob 对象的 uri 视做下载处理,而在 IE 中彷佛不能这样,因此须要单独调用 navigator.msSaveBlob 方法,而低版本的 IE 甚至不能支持 blob 对象,须要使用浏览器提供的特定 API 来实现保存功能。浏览器