How to get the current function's name or linenumbers in V8

448 views Asked by At

I want to dynamically hook the information about the current executing function in V8.

For example the function name, line number, or file name, etc.

Is it possible for V8 to set some breakpoints to get this information when the page or app is running in it?

For example:

< script >
  function f1() {
    ...
    f2();
    ...
  }

function f2() {
  ...
}
f1(); 
< /script>

When f1() is executing, get the f1's function name and linenumbers; then f1() call f2(), f2() is executing, get the f2's function name and linenumbers; finally, when f2() is finish, back to f1(), get the f1()'s function name and linenumbers.

That is what I mean by "information about the current executing function in V8".

1

There are 1 answers

4
David P. Caldwell On

You can use new Error().stack and then parse the output.

(function() {
    var b = function() {
        var trace = new Error().stack.split("\n")[1];
        console.log(trace);
    };

    var a = function() {
        b();
    };

    a();
})();

Output:

at b (file:///home/inonit/tmp/stack.html:6:16)

From there you can extract the file name, function name, line number, and column number if you like.