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:
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!
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:
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:
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.