Umar Iqbal
Umar Iqbal

Reputation: 689

How does Debugger.getScriptSource work?

I'm trying to run chrome debugger to gather deobfuscated JavaScripts but it returns a large number of chunks for a script. I want to know how does chrome divides one JavaScript file to multiple chunks? What exactly is one chunk of a script?

I am aware that for each script file, script tag, and eval() function separate chunks will be created. I just want to pinpoint all possible cases for which chunks are created. For example, does lazy parsing also creates chunks for some functions?

It would be great if somebody can point me to some documentation about how the process works.

Chrome debugging protocol API used

Upvotes: 3

Views: 1297

Answers (1)

Gideon Pyzer
Gideon Pyzer

Reputation: 23958

The Debugger.scriptParsed event is what generates the scriptId for each script found. Each script file parsed will fire the event and should receive a unique id. As well as individual script files, each instance of a <script> tag within a page source will also get its own id.

There are a number of parameters the event callback gets passed. You can inspect all the arguments by logging out the arguments object. For example, you'll get a url back for a script file and startLine gives you the offset for <script> tags that appear in an HTML resource.

on('Debugger.scriptParsed', function() {
    console.log(JSON.stringify(arguments, null, 2)(
});

Investigation

In response to your updated question, my understanding is that in debugger mode it will attempt a full parse and not to try to optimise with a pre-parse. I wasn't able to really understand the v8 code base, but I did a little testing.

I created an HTML page with a button, and a separate script file. I executed one function immediately after page load. Another function is executed on click of button.

document.addEventListener("DOMContentLoaded", () => {
    document.getElementById('clickMe').addEventListener('click', () => clicked);
});

I inspected the output from Debugger.scriptParsed. It parsed the script file straight away. Upon clicking the button, there were no additional output entries. If I changed the handler to invoke the clicked called dynamically using eval, it did output a new script chunk.

eval('clicked()');

This makes sense as there's no way for the parser to know about it until it's executed. The same applies to an inline handler, e.g. onclick="doSomething()"

Other chunks I noticed were Chrome Extension URIs and internals URIs from chrome.

Upvotes: 7

Related Questions