我使用document.implementation.createHTMLDocument()
函数创建一个HTML文件。像这样:
var doc = document.implementation.createHTMLDocument("My New Document");
我想下载这个新创建的HTML文档。我尝试过:
var link = document.createElement('a');
link.href = doc;
link.download = 'newDoc.html';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
但是不起作用。它将我重定向到myDomain.com/[object HTMLDocument]
。如何下载此文件?
答案 0 :(得分:2)
几个阶段。
下面的例子。
const bt = document.querySelector('button');
bt.addEventListener('click', () => {
//lets create some document
const doc = document.implementation.createHTMLDocument("My New Document");
const hello = doc.createElement('p');
hello.innerText = 'Hello';
doc.body.appendChild(hello);
//now get it's contents and place into a blob
const blob = new Blob([doc.documentElement.innerHTML], {
type: 'text/html'
});
//now convert to url
const docUrl = window.URL.createObjectURL(blob);
//were done, lets create a href to this and download
const aclick = document.createElement('a');
aclick.href = docUrl;
aclick.download = 'download.html';
aclick.click();
//tidy up
window.URL.revokeObjectURL(docUrl);
});
<p>Click button below to download some HTML</p>
<button>download</button>
答案 1 :(得分:0)
您不能在filename
中附加URL
,因为使用HTML File
创建的createHTMLDocument()
不是实际的HTML文件,并且不是服务器上的 Javascript HTMLDocument对象。
您可以使用Data URI,如下所示,Complete Tutorial Here..
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/html;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
// Start file download.
download("newDoc.html","<html><head><title>Hello</title></head><body>Hello World!</body></html>");
注意:下载后,功能
encodeURIComponent()
不会影响HTML。
答案 2 :(得分:0)
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
// Start file download.
function myFunction(){
let html = document.getElementById("textarea").value;;
download("hello.html", html);
}
<textarea id="textarea" placeholder="Type your HTML here..."><h1>WORKING?????</h1></textarea>
<button onclick="myFunction()">GET FILE</button>