Use JS to download the text content as an html file

A simple download Html page, I have found many methods, but none of them are satisfactory (some need back-end assistance, some need cross-domain).

Implementation:

var eleTextarea = document.querySelector('textarea');
var eleButton = document.querySelector('input[type="button"]');

// 下载文件方法
var funDownload = function (content, filename) {
    
    
  //content是要下载页面的html代码,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);
};
//判断浏览器是否支持a标签的download属性
if ('download' in document.createElement('a')) {
    
    
    // 作为test.html文件下载
    eleButton.addEventListener('click', function () {
    
    
        funDownload(eleTextarea.value, 'test.html');    
    });
} else {
    
    
    eleButton.onclick = function () {
    
    
        alert('浏览器不支持');    
    };
}

insert image description here

Guess you like

Origin blog.csdn.net/Macao7_W/article/details/125853420