function download(filename, text) { var pom = document.createElement('a'); pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); pom.setAttribute('download', filename); if (document.createEvent) { var event = document.createEvent('MouseEvents'); event.initEvent('click', true, true); pom.dispatchEvent(event); } else { pom.click(); } } var data = { a:11, b:[{a:1,b:3}] } download("data.txt",JSON.stringify(data));
通過a標簽的download屬性,將數據保存到href屬性中,模擬點擊事件實現文件下載;
href屬性中也可以直接防止下載文件的地址;