有没有一种方法可以实时跟踪网站源代码的类更改?

时间:2020-08-20 01:10:26

标签: javascript python google-chrome-extension

我正在开发chrome扩展程序,如果网站源上的特定类已更改,则该扩展程序必须触发一个过程。有一种实时的方法吗?

1 个答案:

答案 0 :(得分:0)

使用Gabriele Romanato's blog所示的MutationObserver界面

Chrome 18 +,Firefox 14 +,IE 11 +,Safari 6 +

// The node to be monitored
var target = $( "#content" )[0];

// Create an observer instance
var observer = new MutationObserver(function( mutations ) {
  mutations.forEach(function( mutation ) {
    var newNodes = mutation.addedNodes; // DOM NodeList
    if( newNodes !== null ) { // If there are new nodes added
        var $nodes = $( newNodes ); // jQuery set
        $nodes.each(function() {
            var $node = $( this );
            if( $node.hasClass( "message" ) ) {
                // do something
            }
        });
    }
  });    
});

// Configuration of the observer:
var config = { 
    attributes: true, 
    childList: true, 
    characterData: true 
};

// Pass in the target node, as well as the observer options
observer.observe(target, config);

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