通过MutationObserver 开发chrome浏览器扩展的实例

2025-09-21 17:45:58 54 分享链接 开发笔记 浏览器扩展

在content.js中添加如下代码

try {
    console.log('测试脚本执行');
    const observer = new MutationObserver((mutationsList) => {
        console.log('MutationObserver 回调函数被调用');
        for (const mutation of mutationsList) {
            if (mutation.type === 'childList') {
                const addedNodes = Array.from(mutation.addedNodes);
                nodesAdded(addedNodes);
                const removedNodes = Array.from(mutation.removedNodes);
                nodesRemoved(removedNodes);
            }else if(mutation.type === 'attributes'){
                nodeAttributes(mutation);
            }
        }
    });

    // 开始监听 document.body 及其子节点的变化
    observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeOldValue: true, attributeFilter: ['src'] });
} catch (error) {
    console.error('脚本执行被中断:', error);
}

// 新增的节点(子节点的添加)
function nodesAdded(addedNodes){
    //console.log('新增的节点:', addedNodes);
    nodesAddedImages(addedNodes);
}

// 移除的节点(子节点的删除)
function nodesRemoved(removedNodes){
    //console.log('移除的节点:', removedNodes);
}

// 单个节点的属性变化
function nodeAttributes(mutation){
    // 获取属性发生变化的节点
    const changedNode = mutation.target; 
    console.log('属性变化的节点:', changedNode);
    // 其他关键信息
    const changedAttrName = mutation.attributeName; // 变化的属性名(如 "class"、"style")
    const oldValue = mutation.oldValue; // 变化前的属性值(需配置 attributeOldValue: true 才会有值)
    console.log(`节点 ${changedNode.tagName} 的 ${changedAttrName} 属性发生变化,旧值:${oldValue}`);
}

// 筛选出新增的图片节点
function nodesAddedImages(addedNodes){
    addedNodes.forEach(node => {
        // 先确保是元素节点(避免非元素节点调用 matches 报错)
        if (node.nodeType === 1) {
            if (node.matches('div[data-testid="message_image_content"] picture img[alt="image"]')) {
                console.log('匹配的 img 节点:', node);
            }
        }
    });
}

通过MutationObserver 开发chrome浏览器扩展的实例