Anton
Anton

Reputation: 137

Get the body of an external website with javascript

I am trying to get the body of an external website. I got this working for another website using the querySelectorAll() method. However, the website I am trying to get the body from does not have any classes/id's (it's just some text). So far I came up with this:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == xml.DONE) {
        var container = document.implementation.createHTMLDocument().documentElement;
        container.innerHTML = xml.responseText;
        var body = container.body.innerText;
        console.log(body);
    }
};
xhr.open("POST", artist_url);
xhr.send(null);

But I get this error:

Uncaught TypeError: Cannot read property 'innerText' of undefined
at XMLHttpRequest.xhr.onreadystatechange

What am I doing wrong / not understanding?

Thanks in advance!

Upvotes: 0

Views: 74

Answers (1)

GirkovArpa
GirkovArpa

Reputation: 4912

You've to refer to container.ownerDocument.body, container is actually the <html> element (providing the response text contains a body tag). Notice also, that onreadystatechange fires multiple times during the AJAX request, check the readyState property (4) and the status (200), or use onload and check the status before trying to use the response.

... and the AJAX call can success only when the source page has CORS headers enabled, otherwise a cross-origin request fails.

Teemu

Upvotes: 1

Related Questions