jack
jack

Reputation: 267

how to evaluate http response received in fetch api

How can we evaluate the http response retrieved in fetch api (Is there a way to not send cookies when making an XMLHttpRequest on the same origin?)?

we get access to the responseText as a result of the fetch call. Now can we do programmatically (possibly via an api call on responseText) things the browser does (called page loading) like downloading the images, css files etc and evaluating the scripts and possibly making xmlhttprequests if there are any.

I want to get to the html content of the page when all this is done, i.e., equivalent to when the browser goes from "loading" state to "complete" after finishing all this.

I hope the question is clear.

Upvotes: 2

Views: 1796

Answers (1)

rphv
rphv

Reputation: 5537

You could render the response.text() into an <iframe> (with visibility: hidden if you wish). Then you can manipulate the new doc with all the standard functions:

<!DOCTYPE html>
<html>

<head>
  <title>This is the page title</title>
  <meta charset="UTF-8">
  <meta name="description" content="Free Web Help">
  <meta name="keywords" content="HTML,CSS,XML,JavaScript">
  <meta charset="utf-8">
</head>

<body>

</body>

<script>
  var img = new Image();
  img.src = "http://cdn.sstatic.net/stackoverflow/img/[email protected]";
  document.body.appendChild(img);
  fetch("so.html")
    .then(function(response) {
      return (response.text());
    })
    .then(function(responseText) {
      // limit the recursion depth to 1
      if (!window.frameElement) {
        var newDoc = document.createElement('iframe');
        document.body.appendChild(newDoc);
        newDoc.contentDocument.write(responseText);
      }
    });
</script>

</html>

To try this yourself, you can save this code as so.html and access it on your local web server, or you can check it out here.

Upvotes: 2

Related Questions