java and selenium for element with div that scrolls

Looking for a way to scroll within an inner window (i.e. div)? Check out this helpful website: How to scroll to an element inside a div?

I came across some Javascript solutions, but I'm struggling with passing values back to Java while using the executor. My code involves a div window with hidden elements at the bottom that only appear when scrolled to. To tackle this, I attempted scrolling a large number in hopes of covering all possible scenarios.

My current approach involves scrolling to the top and then proceeding like this:

    String sid = rolesScroller.getAttribute("id");
    js.executeScript("document.getElementById('" + sid + "').scrollTop -= 1000");
    js.executeScript("document.getElementById('" + sid + "').scrollTop += 1000");
    waitForXPathVisibility("Scroll", ROLES_SCROLLER_X);

Is this method acceptable, or should I determine the exact amount to scroll and do so precisely?

I noticed there's element.scrollHeight property. Do scrollTop values range from 0 to scrollHeight? Are both units measured in pixels?

The div elements contain nested nodes which can expand to reveal more contents. Every time I search for a value, I have to ensure everything is visible by scrolling as mentioned above. While my current approach works to some extent, I encounter StaleElementException occasionally after scrolling. Performing a waitForStaleElement() sometimes results in errors stating that the element didn't go stale. Is there a way to confirm that all actions are completed after executing JavaScript to avoid such issues?

To Summarize

  1. Can JavaScript variables be passed back to Java when using the executor from Java/Selenium, especially for subsequent JavaScript commands?

  2. How can the completion of a JavaScript command be assured before proceeding, preventing potential Stale Element exceptions when accessing elements in the scrolled div?

Answer №1

It appears that the container is dynamically generated as you scroll down. To address this, try scrolling the last element to the top using scrollIntoView and then wait for a new element to appear at the end:

WebDriverWait wait = new WebDriverWait(driver, 5);
JavascriptExecutor jse = (JavascriptExecutor)driver;

// Locate the last element
By lastChild = By.cssSelector("#list > div:last-of-type");
WebElement elem = driver.findElement(lastChild);

// Scroll the last element to the top
jse.executeScript("arguments[0].scrollIntoView(true);", elem);

// Wait for a new element to appear at the end
wait.until((WebDriver drv) -> !elem.equals(drv.findElement(lastChild)))

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

JavaFX - Create a custom CellFactory by combining TextFieldTableCell.forTableColumn() with another unique implementation

My TableColumn setup is as follows: TableColumn<Foo, String> colStatus = new TableColumn("Status"); colStatus.setCellValueFactory(new PropertyValueFactory<>("statusElement")); In order to make the cell editable on this table, I am using the T ...

Error encountered while populating GridView with images due to insufficient memory allocation

I am encountering an issue with my app that loads images in a GridView. Depending on the number of images I have in my array, I am facing the dreaded java.lang.outofmemory error causing the app to crash. I have implemented an ImageAdapter where the image ...

What is the best way to retain an edited value within the same index without moving it to a different

One issue I encounter is when attempting to save an edited value on the same index, but the value cannot be saved because the editing mode has not been closed. This pertains to a TypeScript File where I need to save the edited value in a selected Command ...

Why am I not getting any results when using the Selenium driver.find_elements_by_xpath method?

These are the specifications I am using for the question below: selenium (version 3.141.0) Chrome (version 76) wsl python (version 3.5.3) The objective of the script below is to extract the Reference, Plant, Direction, and Disease columns for each dropdo ...

The loading of charts and animations is sluggish on mobile devices

My Chart.js chart starts with 0 values and updates upon clicking submit to load data from an external database. While this works efficiently on a computer browser, the load time is significantly longer when accessing the page on a mobile device. It takes a ...

Exchange of Fusion Chart

Attempting to perform a fusion chart swap with asp has proven to be challenging. The alternative approach involves rendering the fusion chart first and then using onmousedown to replace the chart with an image. However, this method is also encountering i ...

Create an instance of an object containing arrays as properties

Is there a way to initialize an object in JavaScript with properties that are arrays? I am looking to create an object structured like this: foo = { prop1: [0, 1], prop2: [1, 1], prop3: [0] } My scenario is as follows: - If a property doesn't exist ...

Implementing React Localized Global Styling

Is there a way to confine the global styles of a module to just one file? For example, I want to adjust the width of an element in a react module but only within one specific file. Unfortunately, inline styles are not an option :/ Edit for clarification: ...

Failed to build development environment: Unable to assign the attribute 'fileSystem' to a null value

I'm attempting to launch an Ionic 2 Application, but I keep encountering this error when running ionic serve Error - build dev failed: Unable to assign a value to the 'fileSystem' property of object null Here is the complete log: λ ion ...

Which is better for managing checkbox state in React - react-bootstrap or material-ui?

Currently, I am working on a project that involves using checkboxes within a component to display products based on specific features selected by the user. I am seeking advice on how to effectively manage the checkboxes and their corresponding state inform ...

Javascript is sometimes unable to access data created by an ajax script

My Jquery Ajax script generates an HTML table in a situation. Another script filters the table column by providing a dropdown with unique values in that specific column. The filter script works fine with static content on the HTML page but is unable to re ...

Incorporate the key as a prop within a Child Component in a React application

I am trying to display a list of elements in React, where the key of each element is used as an index in front of the item. However, when I try to access props.key, it just returns undefined. Does anyone have any suggestions on how to access the key proper ...

Creating an array of Map<String, Object> objects in Java

Is this Problem Familiar: Cannot create an array of LinkedLists in Java…? I am trying to utilize the following method: executeBatch(Map<String,Object>[] batch) However, I am struggling to comprehend how to generate an array of Map<St ...

Tips for consistently using identical browser instances and assigning distinct links to each?

Here is a code snippet I have: import concurrent.futures from concurrent.futures import ThreadPoolExecutor from selenium import webdriver from selenium.webdriver.chrome.options import Options links = ['https://en.wikipedia.org/wiki/File:Mechaniti ...

Tips for importing a Multimaterial .dae file in three.js?

I am facing an issue while trying to load a model with multiple materials. I want to access the array of materials but my current approach is not working as expected. loader.load('./dae/tenis.DAE', function ( collada){ dae = collada.scene; ...

Restrict the maximum and minimum time that can be entered in an HTML input

I've implemented a basic code feature that allows users to input minutes and seconds on my React website. <div> <span> <input defaultValue="0" maxlength="2"/> </span> <span>m</span> <spa ...

The mongoose find query is coming back with an empty array, even though there is data present in the

My goal is to update commodity data in my stockrecord collection by adding the quantity of a commodity if it already exists in the collection. However, I encountered an issue where the find method returns an empty array even for existing data. Here is th ...

Determining a User's Connection Status in ReactJS: Cellular Network or WiFi?

Are there any tools or applications available that can determine if a user is connected to WiFi or using a cellular network? ...

The Field Projection operation is not taking into account the batchSize field name

I have a collection called user_batch which contains the following two documents: [{ _id: ObjectId("594baf96256597ec035df23c"), name: "Batch 1", batchSize: 30, users:[] }, { _id: ObjectId("594baf96256597ec035df234"), name: "Batch 2", batch ...

"Webpack error: Including a comma within a string leads to a syntax problem when bund

I'm attempting to merge this file into my main JS. var constants = { height: 600, width: 400, default_bezier = "[ { \"startPoint\" : [51.6503017608354,203.464445873753], \"endPoint\" : [-52.41285540263849,202.372456432 ...