Search code examples
puppeteerpuppeteer-sharp

Puppeteer Function to PuppeteerSharp


I am new to puppeteersharp and puppeteer in general. I am trying to convert a function that is used in puppeteer to puppeteerSharp and i am wondering how to do it. Here is the puppeteer function(this one scroll down to the end of the page):

async function autoScroll(page){
await page.evaluate(async () => {
    await new Promise((resolve, reject) => {
        var totalHeight = 0;
        var distance = 100;
        var timer = setInterval(() => {
            var scrollHeight = document.body.scrollHeight;
            window.scrollBy(0, distance);
            totalHeight += distance;

            if(totalHeight >= scrollHeight){
                clearInterval(timer);
                resolve();
            }
        }, 100);
    });
});

Anyone Can please tell me how can i manage to get this to work with puppeteerSharp? Kind Regards


Solution

  • You can call EvaluateFunctionAsync and pass that function as string.

    await page.EvaluateFunctionAsync(@"async () => {
        await new Promise((resolve, reject) => {
            var totalHeight = 0;
            var distance = 100;
            var timer = setInterval(() => {
                var scrollHeight = document.body.scrollHeight;
                window.scrollBy(0, distance);
                totalHeight += distance;
    
                if(totalHeight >= scrollHeight){
                    clearInterval(timer);
                    resolve();
                }
            }, 100);
        });
    }");