Created
August 30, 2023 14:20
-
-
Save moinulmoin/1668a285495043ac685dd4087d9424aa to your computer and use it in GitHub Desktop.
AutoScroll down - Puppeteer Page
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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