如何在javascript中从[object HTMLDocument]中获取内容



我试图从url中获取HTML数据(我从字符串中解析了该数据,因为链接到它的javascript文件不起作用(,然后将响应加载到文档中。然而,当我在控制台中记录响应时,我会得到html内容,但当我加载文档时,它会显示[object HTMLDocument]。

这是我的代码-

fetch(url)
.then(res => res.text())
.then(data => {
let parsedRes = (new window.DOMParser()).parseFromString(data, "text/html")
processData(parsedRes, url)
});
function processData(response, urlPath){
console.log(response)
document.querySelector("html").innerHTML = response;
window.history.pushState({}, "", urlPath);
};

如何做到这一点?

response是一个文档对象,innerHTML需要一个字符串。您可以使用response文档的内部html。。。

fetch(`data:text/html;,<html><head>u003cscript src="https://code.jquery.com/jquery-3.6.0.min.js">u003c/script><style>div {color:red;}</style></head><body>
<div>This is a red div</div>u003cscript>$('div').append('<span style="color:green">(green span)</span>');u003c/script></body></html>`)
.then(res => res.text())
.then(data => {
let parsedRes = (new window.DOMParser()).parseFromString(data, "text/html")
setTimeout(function(){
processData(parsedRes, 'url');
}, 2500);
});

async function processData(response, urlPath){
console.log(response)
document.querySelector("html").innerHTML = response.querySelector("html").innerHTML;
var scripts = document.querySelectorAll("script");
for (var i = 0; i < scripts.length; i++){
if (scripts[i].src){
let script = document.createElement('script');
script.src = scripts[i].src;
scripts[i].parentNode.insertBefore(script, scripts[i]);
if (!scripts[i].async){
await new Promise((resolve, reject) => {
script.onload = ()=>resolve(true);
script.onerror = ()=>reject(false);
});
}
}
else{
let script = document.createElement('script');
script.innerHTML = scripts[i].innerHTML;
scripts[i].parentNode.insertBefore(script, scripts[i]);

}
}
window.history.pushState({}, "", urlPath);
};
<div>This is the original div</div>

最新更新