[Protractor][Scroll] I need assistance with scrolling my webpage using a while loop. Could someone please help me troubleshoot the code?

When this function is called, it initiates scrolling and then pauses the browser for a 2-second period.

   scrollToElement(webElement: any) {
        browser.executeScript('window.scrollTo(0,400);').then(()=>{
            console.log("sleeping"+ browser.sleep(2000));
        }).catch((err)=>{
            assert.fail("failed to scroll");
        }); 
    }

Snippet for calling the function:

while(!(arr[0]===arr[2])){
            console.log('scroll');
            utils.scrollToElement(this.scrollUpLink);
            countTop = utils.getTextfrom(this.getTotalcountOnTop);
             let arrIn=countTop.split(" ");
             arr[0]=arrIn[0];
             arr[2]=arrIn[2];
             console.log(" Indisde :"+arr[0]+ " "+ arr[2]);
        }

In this scenario, I am verifying the equality of two strings and continuously scrolling until they match.

The result displayed is as follows:
scroll
 Indisde :24 434
scroll
 Indisde :24 434
scroll
 Indisde :24 434
scroll
 Indisde :24 434

Answer №1

There seem to be some issues in your code implementation. Specifically, the handling of Promises and the incrementing of the value by 400 in window.scrollTo(0,400);.

You also appear to be using sleep() within then(), which may not be ideal. I have modified your code based on your original version and it is functioning correctly. Please update your code accordingly and give it a try:

// Defining 'driver' variable
var driver = null;

// Function for scrolling to an element
async function scrollToElement(xValue, yValue) {
    await driver.executeScript('window.scrollTo('+xValue+', '+yValue+');')
}

// Function which triggers scrolling with a delay of 2 seconds per scroll 
async function doScroll() {
    // Setting up the driver
    driver = await browser.setup('chrome');
    // Opening Chrome and navigating to google.com
    await driver.get('http://www.google.com');
    // Performing a search on Google
    await driver.findElement(By.name('q')).sendKeys('alicse3'+Key.ENTER);
    // Invoking the scrolling function
    let i = 0, xValue = 0, yValue = 100;
    while(i++ <= 5) {
        await scrollToElement(xValue, yValue+=100);
        await console.log("=> The 'i' value is " + i);
        await driver.sleep(2000);
    }
}

// Triggering the scrolling process
doScroll();

I believe this revised version will resolve the issues you were facing. Feel free to test it out...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

lint-staged executes various commands based on the specific folder

Within my project folder, I have organized the structure with two subfolders: frontend and backend to contain their respective codebases. Here is how the root folder is set up: - backend - package.json - other backend code files - frontend - p ...

Welcome to the awe-inspiring universe of Typescript, where the harmonious combination of

I have a question that may seem basic, but I need some guidance. So I have this element in my HTML template: <a href=# data-bind="click: $parent.test">«</a> And in my Typescript file, I have the following code: public test() { alert( ...

Where did protractor-jasmine 2-fail-whale go off to?

It seems that both their github and the npm registry are showing a 404 error. https://github.com/radialanalytics/protractor-jasmine2-fail-whale https://www.npmjs.com/package/protractor-jasmine2-fail-whale ...

Connect store variables to components using Angular's ngrx

I am attempting to link the location variable in my component to another variable in the store using a selector with ngrx v13 in Angular. However, when I include the variable with the property in the HTML, I encounter an error: Error message: Property &ap ...

What sets apart a class from a service in NativeScript?

I am embarking on the journey of learning Nativescript + Angular2, and while reading through the tutorial, I came across this interesting snippet: We’ll build this functionality as an Angular service, which is Angular’s mechanism for reusable classes ...

Dynamic starting point iteration in javascript

I'm currently working on a logic that involves looping and logging custom starting point indexes based on specific conditions. For instance, if the current index is not 0, the count will increment. Here is a sample array data: const data = [ { ...

"Angular application does not have a reference to elementRef after completion of build

I have encountered an issue with my component template. I am trying to select an SVG element using ElementRef and it seems to work fine. However, when I build the app and open it, the elementRef is null. @Component({ selector: 'app-svg&apos ...

Prevent selection on a specific column in ngx-datatable

My ngx-datatable has 4 data columns and a delete button column to remove rows from the table. https://i.stack.imgur.com/MbGDM.png Here is the HTML code: <ngx-datatable *ngIf="!isLoading" #table class="data-table" [scrollbarH]="true" [rows]="data" [co ...

Issue with Angular 2 HTTP provider: Observable subscription not triggering

I'm struggling to trigger the .subscribe() method on an observable in Angular 2. I have a provider that uses the Http Service to fetch data and return an observable for the controller to subscribe to. I can't figure out why the subscribe functio ...

Having trouble starting Google Chrome version 61 in CentOS 7 with Selenium WebDriver?

System Information: Operating System: Centos 7 Browser: GOOGLE CHROME V61 Automation Tool: SELENIUM WEBDRIVER 3.5.3 Driver: ChromeDriver 2.30/2.32 Attempted to run Google Chrome manually inside Jenkins slave environment google-chrome --no-sandbox --dis ...

Using React hooks and Typescript: I was expecting to see an assignment or function call, but instead, an expression was

After working as a React developer for quite some time, my workplace recently introduced Typescript, which I am still getting familiar with. I implemented a custom hook for managing cookies, but the function it returns is generating an error. Here's ...

When running a Maven test using Selenium TestNG with JavaSE-17, the test results are not displayed

Issue with Selenium TestNG Maven Test Results Display I am encountering an issue where my Selenium (version selenium-server-4.3.0) project is not displaying the test results properly. Here is the environment setup: Eclipse IDE for Java Developers Version ...

The Firefox driver failed to pass verification for usage in Firefox and has consequently been deactivated

Ever since the latest update to Firefox version 43, I have been encountering an error message when attempting to run an application with Webdriver: "Firefox webdriver could not be verified for use in Firefox and has been disabled". Despite setting xpinst ...

What prevents us from returning Observable.of(false) in the catch block within the canActivate function?

In order to protect certain routes (admin), I utilize the canActivate feature. In this scenario, I employ an authGuard class/function: The issue arises when attempting to return an observable of boolean using: return Observable.of(false);. This approach d ...

Every time I run my automated tests, I consistently encounter the error message "Disable Developer Mode Extension" while using mobile emulation on Chrome 2.21 driver

Take a look at some sample code: System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\chromedriver.exe"); DesiredCapabilities capabilities = DesiredCapabilities.chrome(); //Although this line was added to disable exten ...

Is it possible to utilize a partial entity for saving with TypeORM?

My current table structure looks like this: --changeset 0004-order:ccushing create table if not exists "order"."order" ( id uuid primary key not null default uuid_generate_v4(), state uuid re ...

Tips on preventing external JavaScript execution and site requests in PhantomJS

I'm currently conducting tests on a website in search of any potential issues. Just to clarify, I am utilizing phantomjs with ghostdriver in selenium through C# Everything is functioning properly, but I want to optimize the speed. After checking the ...

What is the reason behind the mandatory credentials option for the CredentialsProvider?

When using NextAuth.js with a custom sign in page, some code examples for the credentials provider do not include the credentials option in the CredentialsProvider. According to the documentation (here), the credentials option is meant to automatically "ge ...

No search results appear when the search button is pressed in Python using Selenium

After successfully automating Edge (and Chrome) to navigate to the correct page for searching broadband prices and entering a postcode into the search box, a problem arises when clicking the search button - it fails to display the results. The goal is to o ...

What exactly is the issue with using selenium in conjunction with python?

After running the code, it takes approximately 5-6 seconds to execute but then nothing happens. Although there are no error messages, the code does not appear to be functioning properly. I urgently need assistance as I have a project due in one month. fro ...