2

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.

Community
  • 1
  • 1
jack
  • 227
  • 1
  • 3
  • 11

1 Answers1

2

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/apple-touch-icon@2.png";
  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.

rphv
  • 5,409
  • 3
  • 29
  • 47
  • this is great! but the problem is using iframe to load the page means cookies would be sent with the http requests. to avoid cookies, this was the reason i was using fetch api instead of a normal xmlhttprequest in the first place. any alternative solution that would avoid this situation. – jack Aug 27 '15 at 09:02
  • I think this satisfies your use case - here, I'm just writing the `response.text()` returned from the fetch api into an ` – rphv Aug 27 '15 at 17:28