How can I use page inside of my page.evaluate?
Asked Answered
I

1

2

Inside of this method that works with puppeteer, I want to use page but I can't quite work out how to get it inside the Promise.

async scrollList( page ) {
    let results = await page.evaluate( async () => {
        results = await new Promise( async resolve => {
            // next line fails :-(
            await page.mouse.move( 100, 100 );

            // do other stuff
            return resolve( results );
        });
    });

    console.log('Got results: ', results);
}

How can I do this? Right now I'm getting an error saying page is undefined.

Intemerate answered 22/5, 2020 at 10:2 Comment(1)
Related: puppeteer page.evaluate page not definedTroupe
E
2

Problem

You cannot access page as the two runtimes (Node.js and browser) are separated. The page object can only be accessed from within the Node.js runtime.

Solution

You have to expose a function that can access the page object to do that via page.exposeFunction:

await page.exposeFunction('moveMouse', async (x, y) => {
    // page is accessible here
    await page.mouse.move(x, y);
});

You can use that function inside page.evaluate by calling window.moveMouse(100, 100).

Erbil answered 22/5, 2020 at 13:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.