Search code examples
javascriptconsoledevtools

Is there any way to detect changes in Console (Devtools)?


im looking for answers on my question. And i can't find any. So as example:

this.connect = false;

if (this.connect) {
  alert('CONNECTED');
}

If i change this.connect = true in my devtools -> console. It should alert message 'CONNECTED'.

Is there any way to do that? Will be awesome to get this to work!


Solution

  • Edit: Theres no need for a Proxy. Just use defineProperty to define a get/set method for the connected property of the window.

    Hey have a look at this snippet - guess this is a good way to start with.

    // We are using a property _connected to store the value of the connected property
    let _connected = false;
    
    // We are defining a property with the name 'connected' on the this (this = globalThis = window => console dev tool)
    Object.defineProperty(this, 'connected', {
      get: () => _connected,
      set: (value) => {
        _connected = value;
        console.log(`Setting 'connected' to: ${value}`);
      }
    });
    
    // Try using this.connected = $val inside your console.
    this.connected = true;
    this.connected = false;
    this.connected = "foo";


    Using a Proxy like @Jaromanda X suggested is also possible but I guess it is not be best solution because overwriting the window/this/globalThis - scope seems to be impossible:

    const _this = new Proxy(window, {
      set: (target, key, value) => {
          if (key === "connected")
            console.log(`Setting 'connected' to set to ${value}`);
          target[key] = value;
          return true;
      }
    });
    
    _this.connected = true;
    _this.connected = false;
    _this.connected = "foo";