- js将文本内容模拟下载的形式保存到本地
- 自定义文件类型,.json, .html, .txt 等
var eleTextarea = document.querySelector('textarea');
var eleButton = document.querySelector('input[type="button"]');
// 下载文件方法
var funDownload = function (content, filename) {
var eleLink = document.createElement('a');
eleLink.download = filename;
eleLink.style.display = 'none';
// 字符内容转变成blob地址
var blob = new Blob([content]);
eleLink.href = URL.createObjectURL(blob);
// 触发点击
document.body.appendChild(eleLink);
eleLink.click();
// 然后移除
document.body.removeChild(eleLink);
};
if ('download' in document.createElement('a')) {
// 作为test.html文件下载
eleButton.addEventListener('click', function () {
funDownload(eleTextarea.value, 'test.html');
});
} else {
eleButton.onclick = function () {
alert('浏览器不支持');
};
}
示例
- 也可以自行拼接文本下载。可作为轻量内容的本地保存
出处:https://www.zhangxinxu.com/wordpress/2017/07/js-text-string-download-as-html-json-file/