通过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);
}
}
});
}
最近更新
- 2025-09-22 01:46
- 可以直接在content.js里面写一个函数获取blob数据实现自定义下载吗?
- 2025-09-22 00:17
- background.js中可通过注入脚本的方法实现获取blobUrl实现自定义下载
- 2025-09-21 17:45
- 通过MutationObserver 开发chrome浏览器扩展的实例
- 2025-09-21 17:23
- MutationObserver实例中mutation.type为childList时addedNodes节点的遍历方法。
- 2025-09-21 17:21
- MutationObserver实例中mutation.type为childList时addedNodes节点的筛选方法。
- 2025-09-21 17:09
- MutationObserver实例中mutation.type为childList时addedNodes节点具体的方法与属性。
- 2025-09-21 16:56
- MutationObserver实例中mutation.type突变类型为childList时有哪些属性、方法?
- 2025-09-21 16:46
- MutationObserver实例中mutation三种不同突变类型的属性与方法?
- 2025-09-21 16:34
- MutationObserver实例中mutation.type突变类型为attributes时有哪些属性、方法?
- 2025-09-15 18:42
- 用豆包图像生成的功能批量创作小说推文的提示词