Chrome-extension Javascript to detect dynamically-loaded content

前端 未结 2 455
-上瘾入骨i
-上瘾入骨i 2020-12-16 06:13

I\'m implementing a chrome extension app. I want to replace href attribute in tag (on my webapp\'s homepage) with \"#\". The problem is that the tag might

2条回答
  •  失恋的感觉
    2020-12-16 06:55

    The accepted answer is outdated. As of now, 2019, Mutation events are deprecated. People should use MutationObserver. Here is how to use it in pure javascript:

    // Select the node that will be observed for mutations
    var targetNode = document.getElementById('some-id');
    
    // Options for the observer (which mutations to observe)
    var config = { attributes: true, childList: true, subtree: true };
    
    // Callback function to execute when mutations are observed
    var callback = function(mutationsList, observer) {
        for(var mutation of mutationsList) {
            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
    var observer = new MutationObserver(callback);
    
    // Start observing the target node for configured mutations
    observer.observe(targetNode, config);
    
    // Later, you can stop observing
    observer.disconnect();
    

提交回复
热议问题