假设您有以下 HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Save Demo</title>
</head>
<body>
<p>Hello World</p>
<button id="save-btn">Save as HTML</button>
<script src="app.js"></script>
</body>
</html>
当用户单击按钮时,您希望将页面下载为 HTML 文件。
首先,让我们创建一个可重用的下载函数,它接受一个字符串filename 和一个字符串contents,并创建一个名为filename 的文件,其中包含contents。
function download(filename, contents) {
// Create an anchor tag to download the file
const anchor = document.createElement('a');
// Create an href that contains the contents of the file
// encodeURIComponent encodes a text string as a valid component of a URI
anchor.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(contents));
// set the download attribute to download the given filename
anchor.setAttribute('download', filename);
// Anchor tag should be invisible
anchor.style.display = 'none';
document.body.appendChild(anchor);
// Fire the event
anchor.click();
// Remove the anchor tag
document.body.removeChild(anchor);
}
给定"helloworld.txt" 的文件名和"This is a really cool text file" 的内容,该函数将下载具有给定内容的文件helloworld.txt。
现在我们只需要在按钮上创建一个事件监听器,以便在点击时下载 html。
const btn = document.querySelector('#save-btn');
btn.addEventListener('click', (evt) => {
// create a container for the html
const container = document.createElement('div');
// create an html element
const html = document.createElement('html');
// set the inner html of the html element to be the inner html of the document (everything except the <html></html>)
html.innerHTML = document.documentElement.innerHTML;
// append the html element to the container, to keep the <html></html>
container.appendChild(html);
// download the file as index.html
download('index.html', container.innerHTML);
});
这将下载一个包含 HTML 文件中除 <!DOCTYPE html> 之外的所有内容的文件,您可以通过调用 download 来添加它:
download('index.html', '<!DOCTYPE html>' + container.innerHTML);