Basic JavaScript MutationObserver API

By 23rd June 2020 January 10th, 2022 Blog, Tutourial & Tips

We can use the MutationObserver to listen to changes made to a target node. With this ability we can create many useful cases with this API. Below is an example of code listening to the price changes of the Yahoo Finance page for Bitcoin (BTC-USD)

// https://finance.yahoo.com/quote/BTC-USD?p=BTC-USD

// Select the node that will be observed for mutations
const targetNode = document.getElementsByClassName("Mend\(20px\)")[1];

// 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 = function(mutationsList, observer) {
    // Use traditional 'for loops' for IE 11
    for(let 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
const observer = new MutationObserver(callback);

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

// Later, you can stop observing
// observer.disconnect();
// https://www.tradingview.com/chart/?symbol=BINANCE%3ABTCUSDT


// Select the node that will be observed for mutations
const targetNode = document.querySelector("body > div.js-rootresizer__contents > div.layout__area--center > div.chart-container.single-visible.active > div.chart-container-border > div > table > tr:nth-child(1) > td.chart-markup-table.pane > div > div.legend-1WIwNaDF.noWrap-1WIwNaDF > div.legendMainSourceWrapper-1WIwNaDF > div.item-1WIwNaDF.series-1WIwNaDF > div.valuesWrapper-1WIwNaDF > div > div:nth-child(8)");
// Options for the observer (which mutations to observe)
const config = {
    attributes: true,
    childList: true,
    subtree: true,
    characterData: true
};
// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
    // console.log(':::', mutationsList);
    // Output the change
    console.log('::: >>> ', mutationsList[0].target.textContent);
  
};
// 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();

 

Resources: https://www.smashingmagazine.com/2019/04/mutationobserver-api-guide/