I am using Node.js and Puppeteer and have it set up to load a specific page.
This page renders new elements every second and I am adding a MutationObserver to listen and have a function trigger when new elements are added.
If I for example try getItem(mutation) it will log {}, an empty object
But if I try to getItem(mutation.addedNodes[0].textContent) it will log 'NewElement', which is the text content of the new element.
Also trying anything between mutation all the way to mutation.addedNodes[0].textContent results in empty objects/arrays.
Why does the first example not log anything, the object has values since I can reach them by being more specific. Why does it not log the values it holds and the structure of the object.
const runPuppeteer = async (url: string) => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setViewport({ width: 1920, height: 1080 })
await page.goto(url);
await page.exposeFunction('getItem', (a: any) => {
console.log(a)
})
await page.evaluate(() => {
let observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
getItem(mutation.addedNodes[0].textContent) // <--- My question
}
})
observer.observe(document.querySelector('#chatDiv'), { attributes: false, childList: true, subtree: true })
})
}
let myPage = 'http://localhost:3000/home'
runPuppeteer(myPage)
Not all properties of all objects will print with console.log, particularly with builtins. If you want to know all the properties on an object, you can try Object.keys(o) or Reflect.ownKeys
There are also serialization libraries and "objectify" libraries that will try to turn a complex class instance into an explicit json-like Object.
Sometimes classes will have getters, a number will be wrapped as an object, objects will be proxied, etc, so in general the console.log output can be extremely incomplete