How to convert a document to a string?

I need a java script function that converts the document object of the current loaded page back to source. In firefox, this is smth like this:

var doc = document;
var str = (new XMLSerializer()).serializeToString(doc);
alert(str);

But I need a cross browser solution. How to do it?

For example:

<html>
  <body>
    <script>
       alert( asText(document) );
    </script>
  </body>
</html>

:

<html>
  <body> 
    <script>
       alert( asText(document) );
    </script>
</html>

how would you implement the asText function?

+3
source share
2 answers

Why aren't you using document.documentElement.innerHTML?

example

+7
source
function sourceText(){     
 try{
  var O= new XMLHttpRequest();
  O.open('GET', location.pathname, false);
  O.send(null);
  return O.responseText;
 }
 catch(er){
  return '';
 }
}
0
source

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