【问题标题】:Is there any way to detect changes in Console (Devtools)?有什么方法可以检测控制台(Devtools)中的变化?
【发布时间】:2020-12-28 14:58:16
【问题描述】:

我正在寻找我的问题的答案。我找不到任何东西。 例如:

this.connect = false;

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

如果我在我的 devtools -> 控制台中更改 this.connect = true。它应该提醒消息“已连接”。

有没有办法做到这一点?让它发挥作用真是太棒了!

【问题讨论】:

  • 你可以使用Proxy 我猜大概是这样——但是,只有thiswindow,因为控制台中的thiswindow
  • 你能举个例子吗?我从不使用代理。
  • 其实 jns 的回答并没有使用代理,对于新手来说更容易理解

标签: javascript console devtools


【解决方案1】:

编辑:不需要代理。只需使用defineProperty 为窗口的connected 属性定义get/set 方法即可。

嘿,看看这个 sn-p - 猜猜这是一个很好的开始方式。

// 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";

使用像 @Jaromanda X 建议的代理也是可能的,但我想这不是最好的解决方案,因为覆盖 window/this/globalThis - 范围似乎是不可能的:

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"; 

【讨论】:

  • 我认为应该将this 替换为globalThis 以获得跨平台支持。
  • 是的,这就是答案。我从未使用过defineProperty!我需要更多地关注这个话题!谢谢您的回答。就是这个!爱你
猜你喜欢
  • 2013-05-05
  • 1970-01-01
  • 2015-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
相关资源
最近更新 更多