How to create a DOM object from an html page retrieved via XMLHttpRequest?

I am developing a chrome extension, so I have cross-host permissions for XMLHttpRequests for domains for which I am requesting permissions.

I used XMLHttpRequest and got the HTML page (txt / html). I want to use XPath (document.evaluate) to extract the corresponding bits from it. Unfortunately, I cannot build a DOM object from the returned html string.

var xhr = new XMLHttpRequest();
var name = escape("Sticks N Stones Cap");
xhr.open("GET", "http://items.jellyneo.net/?go=show_items&name="+name+"&name_type=exact", true);
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
    var parser = new DOMParser();
    var xmlDoc = parser.parseFromString(xhr.responseText,"text/xml");
    console.log(xmlDoc);
    }
}

xhr.send();

console.log - display debug files in the Chromium JS console.

In the specified JS console. I get the following:

Document
<html><body><parsererror style="display:block;​ white-space:pre;​ border:2px solid #c77;​ padding:0 1em 0 1em;​ margin:1em;​ background-color:​ #fdd;​ color:black"><h3>​This page contains the following errors:​</h3><div style="font-family:monospace;​font-size:12px">​error on line 1 at column 60: Space required after the Public Identifier</div><h3>​Below is a rendering of the page up to the first error.​</h3></parsererror></body></html>

So, how can I use XMLHttpRequest -> get HTML -> convert to DOM -> use XPath for transverse?

Should I use a "hidden" iframe hack to load / receive a DOM object?

+3
1

DOMParser DOCTYPE. , xhtml, <link> /. ? , . , , .

: , div:

var hidden = document.body.appendChild(document.createElement("div"));
hidden.style.display = "none";
hidden.innerHTML = /<body[^>]*>([\s\S]+)<\/body>/i(xhr.responseText)[1];

hidden, , :

var myEl = hidden.querySelector("table.foo > tr > td.bar > span.fu");
var myVal = myEl.innerHTML;
+2

Source: https://habr.com/ru/post/1770412/


All Articles