I am looking to access the function call stack during regular execution instead of only when exceptions occur (unlike new Error().stack). For instance, I already understand that a function named g is triggered with a button click, and its implementation is as follows:
function g() {
// Some code here
g1(); // g1 is a function defined in a different JavaScript file
// More code here
}
If I possess a reference to g and the name for g1, is there a way to identify the source file of g1 using any methods available in Chrome or Puppeteer, along with retrieving the total line count of that file?
You can use Chrome DevTools Protocol integrated with Puppeteer to achieve this. Use Debugger.getScriptSource
to get the source of the target script. Here's a snippet:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('your_url');
await page.evaluate(() => {
function g() {
console.trace();
}
});
const client = await page.target().createCDPSession();
await client.send('Debugger.enable');
const { scriptSource } = await client.send('Debugger.getScriptSource', {
scriptId: 'your-script-id'
});
console.log(scriptSource.split('\n').length); // Total line count
await browser.close();
})();
Replace 'your-script-id'
and 'your_url'
accordingly. Accessing script IDs might involve additional debugging steps.
To accomplish what you're aiming for, Chrome DevTools Protocol via Puppeteer is indeed your ally. However, the direct retrieval of the call stack and file details isn't straightforward due to limitations in JavaScript execution environments.
Here's how you can do it:
- Enable debugging with Puppeteer's CDP session.
- Use
Debugger.getStackTrace
to retrieve the current call stack when running your function.
- Extract the
scriptId
from the stack trace entries, and use Debugger.getScriptSource
to retrieve the source code and calculate the line count.
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('your_url');
const client = await page.target().createCDPSession();
await client.send('Debugger.enable');
await page.evaluate(() => {
function g() {
console.trace(); // Initiate a trace to generate a call stack
}
g(); // Call your target function
});
client.on('Debugger.paused', async ({ callFrames }) => {
const stack = callFrames.map(frame => frame.location);
console.log('Call stack retrieved:', stack);
const { scriptSource } = await client.send('Debugger.getScriptSource', {
scriptId: stack[0].scriptId
});
console.log('Total lines in the script:', scriptSource.split('\n').length);
await client.send('Debugger.resume');
await browser.close();
});
})();
Replace 'your_url'
with the actual URL. Getting accurate script IDs might require you to step through the debugging events more granularly. This approach provides you the stack trace and script source dynamically.