What is the Puppeteer equivalent of window.scrollTo()?
Davide S
davide s profile pic

The Puppeteer equivalent ofwindow.scrollTo() is achieved by using thepage.evaluate() method along with JavaScript code to manipulate the scrolling behavior. Here's a detailed explanation of how to scroll in Puppeteer: 1. Launching a new browser instance and creating a new page:

1
2
3
4
5
6
7
8
9
10
11
12
13

   const puppeteer = require('puppeteer');

   (async () => {
     const browser = await puppeteer.launch();
     const page = await browser.newPage();

     // Perform actions with the page here

     // Close the browser
     await browser.close();
   })();
   

This code sets up a basic Puppeteer script. It launches a new headless browser instance and creates a new page to work with. 2. Scrolling to a specific position: To scroll the page to a specific position, you can use thepage.evaluate() method to execute JavaScript code within the page context.

1
2
3
4
5

   await page.evaluate(() => {
     window.scrollTo(x, y);
   });
   

In this example,window.scrollTo(x, y) is used to scroll the page to the specifiedx andy coordinates. Adjust thex andy values as needed to scroll to the desired position. 3. Scrolling to an element on the page: If you want to scroll to a specific element on the page, you can use thescrollIntoView() method along withpage.evaluate().

1
2
3
4
5
6

   const element = await page.$('your-selector');
   await page.evaluate((el) => {
     el.scrollIntoView();
   }, element);
   

In this code snippet,page.$('your-selector') is used to select the element on the page based on the provided selector. Then,scrollIntoView() is called on the element usingpage.evaluate(), which scrolls the page to ensure the element is visible. 4. Smooth scrolling: By default, scrolling using the methods mentioned above is instantaneous. However, if you prefer smooth scrolling animation, you can use thescrollTo() method with thebehavior option set to'smooth'.

1
2
3
4
5
6
7
8
9

   await page.evaluate(() => {
     window.scrollTo({
       top: 0,
       left: 0,
       behavior: 'smooth'
     });
   });
   

In this example, thescrollTo() method is used to scroll to the top-left corner of the page with a smooth animation. Adjust thetop andleft values as needed to scroll to specific coordinates on the page. By following these steps, you can achieve scrolling functionality in Puppeteer, similar towindow.scrollTo(). Whether you want to scroll to a specific position or scroll to a particular element, Puppeteer'spage.evaluate() method allows you to execute JavaScript code within the page context to manipulate the scrolling behavior.