Search code examples
javascriptprivategoogle-developers-consoleprivate-membersclass-fields

Access private members from developer console?


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?


Solution

  • 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)