Search code examples
mutation-observerspuppeteer

How to inject mutationobserver to puppeteer


I want to trace changed DOM like mutationobserver in headless Chrome. I'm learning the Puppeteer library, but I don't know how to do that.

Is it possible to trace DOM change in Puppeteer?


Solution

  • Well,you can inject custom code to the browser.

    One way:

    await page.evaluate(() => {
       const observer = new MutationObserver(
       function() {
         // communicate with node through console.log method
         console.log('__mutation')
        }
       )
       const config = {
         attributes: true,
         childList: true,
         characterData: true,
         subtree: true
       }
       observer.observe(target, config)
    })
    

    In your node script:

    page.on('console', async (msg) => {
       if (msg.text === '__mutation') {
         // do something...
       }
    })