如何使用 MutationObserver 检测 div 文本何时出现?

How to detect when div text appears with MutationObserver?

提问人:LA_ 提问时间:9/25/2023 更新时间:9/25/2023 访问量:20

问:

我使用以下代码来了解何时加载元素:div

const callback = function (mutationsList, observer) {
  
    for (let node of mutation.addedNodes) {    
      if (!(node instanceof HTMLElement)) continue;    
      if (node.matches('div[class*="textLayer"]')) {    
        ...    
      }    
    }        
};

const observer = new MutationObserver(callback);
observer.observe(target, config);

但页面稍后会加载其内容。所以,我应该等待内容出现:textLayer

<div class="textLayer" style="width: 554px; height: 783px;"></div>

转换为

<div class="textLayer" style="width: 554px; height: 783px;">
    <span style="left: 27.9328px; top: 27.2773px">Some text</span>
    <span style="left: 27.9328px; top: 63.4428px; font-size: 13.0353px; font-family: sans-serif; transform: scaleX(0.905998);">Some other text I am interested in:</span>
    <span style="left: 27.9328px; top: 79.2713px">0349602902309000000123456</span>
    ...
 </div>

我应该如何实现它?文本值是否应作为属性进行监视?

javascript google-chrome-extension mutation-observers

评论


答:

0赞 EzT 9/25/2023 #1

我认为您还需要观察 textLayer div 的子项的变化。所以调整观察者配置

    const config = {
     attributes: true,       // attribute changes
     childList: true,        // additions/removals of child nodes
     characterData: true,    // changes in text
     subtree: true           // watch for all sub elements
    }; 

此外,如果需要,您可以对回调函数进行调整:

    const callback = function (mutationsList, observer) {
        for(let mutation of mutationsList) {
            if (mutation.type === 'childList') {
                // Handle added nodes
                for(let node of mutation.addedNodes) {
                    if(node instanceof HTMLElement) {
                        console.log(node);
                    }
                }
    
                // Handle removed nodes
                for(let node of mutation.removedNodes) {
                    if(node instanceof HTMLElement) {
                        console.log(node);
                    }
                }
            }
            // Handle text changes
            if (mutation.type === 'characterData') {
                console.log(mutation.target.textContent);
            }
        }
    };

    const observer = new MutationObserver(callback);
    observer.observe(target, config);