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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章