Eric
Eric

Reputation: 5215

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

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.

Upvotes: 2

Views: 1296

Answers (1)

Thomas Dondorf
Thomas Dondorf

Reputation: 25230

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).

Upvotes: 2

Related Questions