【问题标题】:How to listen for variable to be declared|defined|available如何监听要声明的变量|定义|可用
【发布时间】:2022-08-17 19:30:17
【问题描述】:

如何“监听”变量已被声明/创建的事件?

从 CSS 我知道我可以在这样的 CSS 类可用时触发:

let logo = document.querySelector(\'.test\');
logo.addEventListener(\'load\', (event) => {
  console.log(\'CSS class .test is defined now!\');
});

与此类似,我正在为变量寻找“querySelector”,例如:

logo = window.hasOwnProperty(\'window.myVariable\');
logo.addEventListener(\'load\', (event) => {
  console.log(\'window.myVariable is defined now!\');
});

用法:我想在外部异步加载的脚本建立有问题的变量后立即触发代码。

编辑:一些背景 在我的网页(我控制的代码)中,我正在从另一个域(我不控制的代码)加载第 3 方 .js 脚本。该脚本比从其域加载更多代码。这个第二个脚本建立一个变量 \'window.something { \"key\":\"value\",...} 然后发出第三个脚本的加载。我想与我的 js 代码进行交互,以便在变量可用时以及在执行第三个脚本之前对其进行修补。 @reyno 建议使用代理。我最新的方法是自己建立变量,然后使用 Proxy 观察变化。但这也不起作用:

<body>
  <script>
    // establish variable 
    window.someVariable={\"someKey\":\"someValue\"};
    
    // set up Proxy listener:
    var targetProxy = new Proxy(window.someVariable,{
      set: function (target, key, value) {
        console.log(`${key} set to ${value}`);
        target[key] = value;
        // change occured, thus 3rd party set values
        // ... add more code here ...
        return true;
      }
    });
    
    // test:
    window.someVariable.someKey=\"test 1\";
    // but the listener doesn\'t get invoked,
    // only if s.o. sets the proxy copy:
    targetProxy.someKey=\"test 2\";
  </script>

  <script src=\"...load external js code here></script>
  <!-- rest of html page ... -->
</body>

即使运行,另一个问题是其他软件,在它自己的弹出窗口中运行,看起来有自己的范围,一个“自己的”window.someVariable,而不是覆盖我的。

  • 请您分享问题的minimal reproducible example,而不是您正在尝试的解决方案?告诉我们你为什么需要这个。
  • 您可以使用Proxy 确定属性何时更改(仅适用于对象).

标签: javascript event-handling dom-events addeventlistener


【解决方案1】:

首先,设置一个自定义事件监听器,我喜欢称之为“通知”。

document.addEventListener("notify", function() {
   console.log('window.myVariable is defined now!');
})

在稍后将加载的脚本中,在创建变量时触发此事件侦听器。

const myVariable = "hello world";
document.dispatchEvent(new Event("notify"));

示例:https://jsfiddle.net/NHerwich/8b4gedxy/

【讨论】:

  • 这要求 OP 有权访问加载的脚本。为什么不确保正确的装载顺序?
  • @evolutionxbox 我没想到 OP 无法访问脚本。如果他这样做,我的回答应该有效。正确的加载顺序是什么意思?
  • 我正在 HTML 中加载第 3 方脚本。在不确定的时间,将在 DOMContentLoaded 之后和 DocumentLoaded 之前加载该脚本。该脚本定义了一个变量“windows.something”。我想尽快对这个 var 采取行动(修补它)。
  • @jamacoe 如果你知道它会在DocumentLoaded 之前,为什么不听呢?
  • @evolutionxbox 特定的第 3 方脚本将在 DocumentLoaded 之前从其域中触发另一个脚本,我想在两者之间采取行动。
猜你喜欢
  • 1970-01-01
  • 2012-04-10
  • 2011-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-04
  • 2013-07-03
相关资源
最近更新 更多