0

I am trying to get mutation observer working in puppeteer. When I log the mutations array I just get an empty object in array like [{}]

Here is my code:

  await page.exposeFunction("puppeteerLogMutation", (mutations) => {
      console.log(mutations);
    });

    await page.evaluate(() => {
      const target = document.querySelector("#SHORTCUT_FOCUSABLE_DIV");
      const observer = new MutationObserver((mutations) => {
        puppeteerLogMutation(JSON.stringify(mutations));
      });
      observer.observe(target, { childList: true });
    });

Other answers I see online say that I need serialize the mutations array into a string before I pass it back into puppeteer with the puppeteerLogMutation function. and I am doing that, but it's still empty data. What would be the best way, to get the entire element that gets added to the dom, as well as the other elements in that element? JSON.parse() doesn't do anything, and mutations.toString() just returns [object Object]

If anyone could help, I would really appreciate it! Thanks!

HunterWhiteDev
  • 141
  • 1
  • 6
  • 1
    What do you expect `JSON.stringify()` to do with a `HTMLElement` / `MutationRecord`? – Andreas Oct 24 '22 at 10:19
  • I keep seeing on other posts that I need serialize it to a JSON string with `JSON.stringify()` – HunterWhiteDev Oct 24 '22 at 10:21
  • 1
    That's not an answer... Please explain what you actually want to do ([What is the XY problem?](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)). And maybe add an example for such an _"other post"_ – Andreas Oct 24 '22 at 10:23
  • I am trying to make a web scrapper that will watch for updates in a discord server and log them into my own datebase. Right now I am just testing mutation observers when I click the awards button on a specific reddit post. Here is 2 example posts: https://stackoverflow.com/questions/55017057/puppeteer-returning-empty-object https://stackoverflow.com/questions/64578952/puppeteer-returns-empty-objects – HunterWhiteDev Oct 24 '22 at 10:30
  • Then read how `MutationObserver` works, what a `MutationRecord` contains and how to (only) grep the text from the relevant elements. – Andreas Oct 24 '22 at 10:35
  • So is that my only option here? I can't dynamically detect the elements within the mutation record? I have to know beforehand what elements I am looking for? – HunterWhiteDev Oct 24 '22 at 10:37
  • None of my comments suggests something like that o.O Head over to https://developer.mozilla.org/ and check their documentation on the mentioned objects. – Andreas Oct 24 '22 at 10:46
  • You can't pass DOM elements back to Node. They have circular references. Either return ElementHandles back to Node or do the clicking in the browser. – ggorlen Oct 24 '22 at 14:42

1 Answers1

0

The solution to this was just pass back innerHTML back into node from puppeteer

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
HunterWhiteDev
  • 141
  • 1
  • 6