Search code examples
scrollcucumberpuppeteer

Cucumber-Puppeteer - Trying to scroll so element will be visible - scroll not working


This is in world.js of a cucumber puppeteer project.

I realized that the the element I'm trying to find with querySelector is not on the screen initially so I want to scroll to right.

So I added code to scroll but screenshot shows scroll did not happen. It also shows that scrollbars are visible.

async getForecastStartColumn(selector, attribute, wait = 0) {
      let forecast;
      await this.page.waitFor(wait);

      await this.page.evaluate(_ => {
         window.scrollBy(3000, 0);
      });

      await this.page.waitFor(1000);
      await this.page.screenshot({ path: './world-177.png', fullPage: true });
      result = await this.page.document.querySelector('div[class="ag-header-cell ag-header-cell-sortable 
          grid-column-header-forecast"]');
   }

//rest of code omitted

Solution

  • Try this code to scroll right.

    const left = $(document).outerWidth() - $(window).width();
    $('body, html').scrollLeft(left);
    
    
    async getForecastStartColumn(selector, attribute, wait = 0) {
          let forecast;
          await this.page.waitFor(wait);
    
          await this.page.evaluate(_ => {
             const left = $(document).outerWidth() - $(window).width();
             $('body, html').scrollLeft(left);
          });
    
          await this.page.waitFor(1000);
          await this.page.screenshot({ path: './world-177.png', fullPage: true });
          result = await this.page.document.querySelector('div[class="ag-header-cell ag-header-cell-sortable 
              grid-column-header-forecast"]');
       }
    
    //rest of code omitted
    

    Edit 1

    I'm using pure js not jQuery. You should know the element which scrolling right and replace 'html' with selector of this element to can scroll to right.

    I'm using .scrollTo(xpos, ypos) to can scroll to left, right, top and button. docs. and using .scrollWidth this is the width of the content of element in pixels. docs. and using .pageYOffset to get current y offset of element to keep this position during scrolling. becouse .scrollTo(xpos, ypos) need to x and y. we need to change xpos only and keep ypos value. docs.

    async getForecastStartColumn(selector, attribute, wait = 0) {
          let forecast;
          await this.page.waitFor(wait);
    
          await this.page.evaluate(_ => {
             const terget = document.querySelector('html');
             terget.scrollTo(terget.scrollWidth, terget.pageYOffset);
          });
    
          await this.page.waitFor(1000);
          await this.page.screenshot({ path: './world-177.png', fullPage: true });
          result = await this.page.document.querySelector('div[class="ag-header-cell ag-header-cell-sortable 
              grid-column-header-forecast"]');
       }
    
    //rest of code omitted