JS 监控网页内容变化

参考突变观察器 - 网络应用程序接口 |多核 (mozilla.org)javascript 监听DOM内容改变事件_监听dom的text变化-CSDN博客

// Select the node that will be observed for mutations
const targetNode = document.getElementById("some-id");

// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
const callback = (mutationList, observer) => {
  for (const mutation of mutationList) {
    if (mutation.type === "childList") {
      console.log("A child node has been added or removed.");
    } else if (mutation.type === "attributes") {
      console.log(`The ${mutation.attributeName} attribute was modified.`);
    }
  }
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();

下面是改变后的:

function wc(){
        // 选择将观察突变的节点
    //var targetNode = document.getElementById('el-test');
    var targetNode = document.querySelector('.xt_video_player_caption');
    // 观察者的选项(要观察哪些突变)
    var config = { attributes: true, childList: true, subtree: true };
 
    // 当观察到突变时执行的回调函数
    var callback = function(mutationsList) {
        mutationsList.forEach(function(item,index){
            if (item.type == 'childList') {
                console.log('有节点发生改变,当前节点的内容是:');
                console.log(item.target.innerHTML);
            } else if (item.type == 'attributes') {
                console.log('修改了'+item.attributeName+'属性');
            }
        });
    };
 
    // 创建一个链接到回调函数的观察者实例
    var observer = new MutationObserver(callback);
 
    // 开始观察已配置突变的目标节点
    observer.observe(targetNode, config);
 
    // 停止观察
    //observer.disconnect();
  }

用于记录mooc字幕

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值