如何从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>