Cannot read Property 'getBoundingClientRect' of Undefined

Asked

Viewed 82 times

1

I’m trying to run a pyppeteer code (basically Puppeteer but for python instead of nodejs), and in it I run a script in the browser initialized through . evaluate(), but something in my javascript is causing the error cannot read Property 'getBoundingClientRect' of Undefined.

I’m running four different evals because joining them doesn’t even work on the Chrome console directly. They are:

    await page.evaluate('''function offset(el) {
    var rect = el.getBoundingClientRect(),
    scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
    scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    return { top: rect.top + scrollTop, left: rect.left + scrollLeft }
}''')
    await page.evaluate('''var vari1 = document.querySelector('.swap-wrap');''')
    await page.evaluate('''var divOffset = offset(vari1);''')
    element_coordinates = await page.evaluate('''() => {
        return(divOffset.left, divOffset.top)
        }''')

Does the fact that the code is asynchronous have to do with (supposedly) the el be treated as Undefined? If I run on the console each of these commands contained in Eval one at a time, I will have the desired result, but here with Eval not.

Code in full: https://ideone.com/zddnWR

And the whole mistake: https://imgur.com/a/3130PW7

1 answer

0

It is necessary to pass the variable as a parameter el also in the first expression of its page.evaluate(..., el) so that it is different from Undefined when executing the function offset:

    el = await page.querySelector(".classe-exemplo")

    await page.evaluate('''function offset(el) {
    var rect = el.getBoundingClientRect(),
    scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
    scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    console.log(el.getBoundingClientRect().right);
    return { top: rect.top + scrollTop, left: rect.left + scrollLeft }
}''', el)

Note that it is necessary to define also before performing the evaluate the definition of the variable el, which should be an element of the open page document. In the example above, use a css query to search for an element with the "class-example".

  • I added this line to my code, and now it raises offset is not defined error on the line await page.evaluate('''var divOffset = offset(vari1);''')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.