Search code examples
javascripthtmlajaxxmlhttprequestfetch-api

How to get content from [object HTMLDocument] in javascript


I'm trying to fetch an HTML data (which I parsed from string because the javascript files linked to it doesn't work) from a url, then load the response into document. However, when I log the response in the console, I get the html content but it displays [object HTMLDocument] when I load the document.

Here is my code -

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);
};

How can this be achieved?


Solution

  • response is a document object, innerHTML expects a string. You could use the inner html of the response document...

    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>