jeffbRTC
jeffbRTC

Reputation: 2069

How to programmatically get the HTML that the Devtools see when clicking on line number?

I'm trying to build a logic that resolves to line number and I attempt to get copy of html this way,

let HTMLdoc = new XMLSerializer().serializeToString(document)

console.log(HTMLdoc)

But I see that it's output different to the one I see on Devtools when clicking on the error stack's line number.

function foo () {
 let stackTrace = (new Error()).stack;
 
 console.log(stackTrace);
}

foo();

You can click Run Code Snippet and open Devtools, then click on the line number you see and Devtools will open the document.

You will find that the Devtools opened document lack CSS and other Div elements.

How do I grab the same one that Devtools gets?

Related

My current hypothesis is that Devtools avoid displaying externally loaded ones. I could be wrong.

If my hypothesis is correct, I need to figure out a regular expression that replaces the externally loaded ones.

Upvotes: 1

Views: 77

Answers (1)

poke
poke

Reputation: 387647

serializeToString(document) will serialize the current document state, including all the changes that may have been applied at runtime. In this case, additional styles were added after the page has been rendered but there may be more drastical changes too that completely remove or redorder things.

When you look at the stack trace from JavaScript, then the browser’s JavaScript engine will attempt to give you information that is closely related to the original source since that’s where your code is coming from. If you use source maps with minified code, the browser is usually even able to tell you where a particular thing came from in the original unminified code even if that code does not even closely match the code that is being executed (e.g. when using a transpiler).

In the end, you cannot really figure out what the browser will tell you where the line of code came from just by looking at the document at runtime. If your code follows very strict rules, you may be able to estimate this with some calculations but this isn’t a safe approach.

Upvotes: 2

Related Questions