How to simulate mouse wheel scrolling in Puppeteer?

I’m working on a Puppeteer script to test scrolling on my webpage. There are two scroll areas: the main browser window and a grid with infinite scroll. I’ve got the browser window scroll working, but I’m stuck on how to simulate mouse wheel scrolling for the grid.

Here’s a simplified version of what I’m doing for the browser window scroll:

async function scrollWindow(page) {
  const viewportSize = await page.viewport();
  await page.mouse.move(viewportSize.width / 2, viewportSize.height / 2);
  await page.evaluate(() => window.scrollBy(0, window.innerHeight));
}

But this doesn’t work for the grid’s scroll. I know jQuery has a way to trigger mouse wheel events, but I need to do this in vanilla JavaScript. Any ideas on how to simulate a mouse wheel scroll event in Puppeteer without using jQuery? Thanks for any help!

hey, have u tried using Element.scrollIntoView()? it’s pretty handy for this kinda stuff. u can do something like:

await page.evaluate(() => {
document.querySelector(‘.grid-item-at-bottom’).scrollIntoView({ behavior: ‘smooth’ });
});

just replace ‘.grid-item-at-bottom’ with whatever selector fits ur grid. works like a charm for me!

I’ve encountered this issue in my Puppeteer projects too. One approach that’s worked well for me is using the page.evaluate() method to execute JavaScript directly in the page context. Here’s a snippet that simulates mouse wheel scrolling:

async function simulateWheelScroll(page, selector, deltaY) {
  await page.evaluate((sel, dy) => {
    const element = document.querySelector(sel);
    if (element) {
      element.scrollTop += dy;
    }
  }, selector, deltaY);
}

You’d call this function with the selector for your grid and the desired scroll amount. For example:

await simulateWheelScroll(page, '.grid-selector', 100);

This method has been reliable for me across different websites and scroll implementations. Just make sure to adjust the selector and scroll amount as needed for your specific use case. Also, don’t forget to add appropriate waits between scroll actions if you’re loading new content.

I’ve tackled a similar issue before, and here’s what worked for me:

Instead of using scrollBy, you can simulate a wheel event directly on the grid element. First, locate the grid element using page.$(), then use page.evaluate() to dispatch a ‘wheel’ event. Here’s a basic example:

async function scrollGrid(page) {
  const grid = await page.$('.grid-selector');
  await page.evaluate((element) => {
    const event = new WheelEvent('wheel', {
      deltaY: 100,
      bubbles: true
    });
    element.dispatchEvent(event);
  }, grid);
}

Adjust the deltaY value to control scroll speed and direction. This method should work for most infinite scroll implementations without relying on jQuery. Remember to add appropriate waits if you’re checking for new content after scrolling.