Access private members from developer console?
Asked Answered
R

1

8

Before, I would use the old convention of naming fields intended to be private with an _ suffix or prefix.

class X{
  constructor() {
    this.privateField_;
  }
  
  privateMethod_() {}
}

Now that real private accessibility is possible with the # symbol, I've been using them a bit.

class X{
  #privateField;

  #privateMethod() {}
}

But one situation I come across is needing to access these private members when debugging. But of course, they're private so I can't unless I write some debug-only wrapper/accessor, which isn't practical if I don't know ahead of time which fields/classes I need to debug. With the _ naming convention, it was easy to bypass intentionally.

Is there a way to bypass the private modifier when using chrome dev console, just like it allows you to use await outside of async blocks?

Roeser answered 25/1, 2022 at 17:20 Comment(4)
If you log the whole object to the console, you should be able to expand it and view all the properties that way.Kocher
Thanks, you're right, I can see field values. But 1) I can't call methods, or 2) access functions on the private fields.Roeser
Private is private. You could define an override of toString() that allowed you to view the values of private fields, and of course you can define methods to be public or call them from public methods and observe their effects (a la unit testing).Tightwad
You can put a breakpoint in a public method and then call that method. When the debugger is paused on the breakpoint within the class, it allows you to access private members of that class.Derickderide
B
4

A workaround is to place a breakpoint in the scope of the class definition (e.g. in a public method, then calling that method). While paused at the breakpoint, you can evaluate code in the debugger console that can access the private field.


And since Chrome 111, this workaround is no longer necessary, you can directly access private fields and methods from the console:

To better facilitate debugging, DevTools now supports evaluating expressions with private class members. (1381806)

Bromide answered 24/3, 2023 at 23:54 Comment(1)
I get the error : Uncaught SyntaxError: reference to undeclared private field or methodMelvinamelvyn

© 2022 - 2024 — McMap. All rights reserved.