How to use JavascriptExecutorDriver In Java
The JavaScriptExecutorDriver is used when certain actions cannot be performed through the usage of Selenium in-built functions and we need some external class to perform such actions. One such action is scrolling of elements into view, that cannot be performed by Selenium in-built functions. In this approach, we will see how we can scroll an element into view using JavascriptExecutorDriver in Selenium.
Syntax:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(“arguments[0].scrollIntoView();”, element);
Here,
- element: It is the element that has to be brought into view by scrolling.
Example of JavascriptExecutorDriver:
In this example, we have opened the Geeks For Geeks (link) website, and then we have found the element having the text ‘Problem of the day‘. Further, we have scrolled to that element using JavascriptExecutorDriver.
//Importing the Selenium libraries
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.By;
public class selenium3 {
public static void main(String[] args) {
//specify the location of the driver
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Vinayak Rai\\Downloads\\chromedriver-win64\\chromedriver-win64\\chromedriver.exe");
//Initialising the driver
WebDriver driver = new ChromeDriver();
//Launch the website
driver.get("https://www.w3wiki.org/");
// Maximize the screen
driver.manage().window().maximize();
// Stating the Javascript Executor driver
JavascriptExecutor js = (JavascriptExecutor) driver;
// Find Problem of the day text
WebElement element = driver.findElement(By.xpath("// *[contains(text(),'Problem of the day')]"));
// Scroll to the specific position
js.executeScript("arguments[0].scrollIntoView();", element);
}
}
Output of JavascriptExecutorDriver:
How to Scroll an Element into View in Selenium?
A high-level programming language that helps users in building web applications is called Java. It is not only used for creating web applications but it can also be used for automating web applications through various automation tools. Selenium is one such tool, which gives users the capability to automate from scratch to end, whether it is opening a web [age, clicking on an element, scrolling the web page, etc. In this article, we will focus on scrolling an element into view through two different approaches, i.e., using JavascriptExecutor and Actions.
Table of Content
- How to Scroll an Element into View in Selenium?
- Using JavascriptExecutorDriver
- Using Actions
- Conclusion
- FAQs