【问题标题】:Listening for changes made to CSS classes in Chrome Devtools在 Chrome Devtools 中监听 CSS 类的变化
【发布时间】:2020-03-26 00:09:05
【问题描述】:

我想检查是否有人通过 Chrome Devtools 修改了元素的 CSS 规则。通常 MutationObserver 就足够了,但是,MutationObserver 只能观察到 inline 样式属性的变化,并且无法检测到元素的 CSS 属性何时已通过 devtools 修改(或者是否添加了新规则检查器样式表)。

用 JavaScript 监听 Chrome Devtools 的 CSS 规则更改的最佳方法是什么?

【问题讨论】:

    标签: javascript css google-chrome google-chrome-devtools cssom


    【解决方案1】:

    我的目标是在 Chrome 扩展程序中使用它。我刚刚发现可以通过 Devtools 监听用户修改:

    //This will only work in the devtools.js file in a Chrome extension
    chrome.devtools.inspectedWindow.onResourceContentCommitted.addListener(function(resource, content) {
     alert(resource.url);
     alert(content);
    });

    更多信息请见here

    【讨论】:

      【解决方案2】:

      检测初始更改的一种间接方法是通过转换事件。当然,这可以绕过,但话又说回来,你在前端所做的一切都可以。

      这个想法的要点是为所有元素添加一个非常短的过渡,并监听它触发的任何过渡事件。

      let timeout = null;
      
      Array.from(document.querySelectorAll('*')).forEach(element => {
        element.addEventListener('transitionstart', () => {
          if (timeout) return;
          timeout = setTimeout(() => {
            console.log('styles changed');
            timeout = null;
          }, 0);
        });
      });
      * {
        transition: all 0.0001s;
      }
      <p>Edit my styles in the console to see messages</p>

      或者,当某些事件被触发时,您可以寻找一种方法来区分所有元素的计算样式,但我看不出有一种方法如何计算不会过于昂贵。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-06
        • 1970-01-01
        • 2023-04-07
        相关资源
        最近更新 更多