I have an HTML body, and I want to get its full inner HTML code before its loading is completed.
<body someproperties>
<!--- some elements --->
<script>
var html = getFullInnerHTMLsomeWay();
</script>
<!--- some elements --->
</body>
So, the question is, how can I get its full inner HTML code before all its child are loaded? I have tried many ideas but no success yet. I also tried to google it but didn't find anything helpful.
Edit: My goal is to replace all instances of a specified text to another text before they displayed to the user.
The first time elements become interactable with (and, for example, viewable from the DOM APIs and by the user) is when the browser inserts them into the DOM.
Given
<body someproperties>
<!--- some elements 1 --->
<script>
console.log(document.body.innerHTML);
</script>
<!--- some elements 2 --->
</body>
you will get the contents of some elements 1, as well as the script tag, but there's no way to get some elements 2 because it hasn't been loaded yet.
You will only be able to get some elements 2 after the <script> tag finishes executing.
The only way I can think of to do something like this would be to completely stop the page from loading, fetch the current page, then parse the response, and then finally load the response into the current page - which would be quite convoluted, and I wouldn't recommend it at all.
It's not exactly what you were asking, but if desirable, you can alter or view the HTML before it gets displayed - use a MutationObserver to watch for appended nodes on the body.
new MutationObserver(() => {
// examine DOM here
// can add and remove nodes as needed, before they get rendered
})
.observe(document.body, { childList: true });