Skip to content

Instantly share code, notes, and snippets.

@moinulmoin
Created August 30, 2023 14:20
Show Gist options
  • Select an option

  • Save moinulmoin/1668a285495043ac685dd4087d9424aa to your computer and use it in GitHub Desktop.

Select an option

Save moinulmoin/1668a285495043ac685dd4087d9424aa to your computer and use it in GitHub Desktop.
AutoScroll down - Puppeteer Page
// ref: https://stackoverflow.com/a/53527984/14491361
/**
* Scrolls the page automatically until either the end of the page
* @param page - The page to scroll.
* @returns A Promise that resolves when the scrolling is complete.
*/
async function autoScroll(page: Page): Promise<void> {
await page.evaluate(async () => {
await new Promise<void>((resolve) => {
let totalHeight = 0;
const distance = 250;
let scrolls = 0; // scrolls counter
const timer = setInterval(() => {
const scrollHeight = document.body.scrollHeight;
window.scrollBy(0, distance);
totalHeight += distance;
scrolls++; // increment counter
// stop scrolling if reached the end
if (totalHeight >= scrollHeight - window.innerHeight) {
clearInterval(timer);
resolve();
}
}, 500);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment