var download = function () { // ダウンロードしたいコンテンツ、MIMEType、ファイル名 var content = 'abc'; var mimeType = 'text/plain'; var name = 'test.txt'; // BOMは文字化け対策 var bom = new Uint8Array([0xEF, 0xBB, 0xBF]); var blob = new Blob([bom, content], {type : mimeType}); var a = document.createElement('a'); a.download = name; a.target = '_blank'; if (window.navigator.msSaveBlob) { // for IE window.navigator.msSaveBlob(blob, name) } else if (window.URL && window.URL.createObjectURL) { // for Firefox a.href = window.URL.createObjectURL(blob); document.body.appendChild(a); a.click(); document.body.removeChild(a); } else if (window.webkitURL && window.webkitURL.createObject) { // for Chrome a.href = window.webkitURL.createObjectURL(blob); a.click(); } else { // for Safari window.open('data:' + mimeType + ';base64,' + window.Base64.encode(content), '_blank'); } } // Click event document.getElementById('download').addEventListener('click', download);
<div id="download">Click to download</div>
#download { display : block; cursor : pointer; background-color: #6DB7F7; width : 180px; line-height : 2em; text-align : center; }