Sometimes we face the problem of scrolling an element as per user view.
JavaScript Executor is used in java code to scroll the page.
There are some scenarios for which we have to perform scroll action:
- Sometimes we require to scroll the page up and then perform actions or activity.
- Sometimes we need to scroll the page down to the bottom and then perform action.
- Sometimes we require to scroll the page to the element and then perform actions or activity.
- We can also scroll the webpage to a particular position using the coordinates of the page.
Scroll Down:
Firstly We need to import javascriptExecutor package:
import org.openqa.selenium.JavascriptExecutor;
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("scroll(0, 200)"); //y value '200' can be altered
Scroll up:
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("scroll(200, 0)"); //x value '250' can be altered
Scroll bottom of the Page:
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollTo(0,Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,document.documentElement.clientHeight));");
Scroll to particular webelement:
Point scrollItem =driver.findElement(By.xpath("Value")).getLocation();
((JavascriptExecutor)driver).executeScript("return window.title;");
Thread.sleep(6000);
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", driver.findElement(By.xpath("Value')]")));
Sample code:
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class PageScrolling {
WebDriver driver;
String URL = "https://www.linkedin.com/" ;
@BeforeClass
public void setUp() {
driver = new FirefoxDriver();
driver.get(URL);
driver.manage().window().maximize();
}
@Test(priority=1)
public void scrollingToBottom() {
driver.navigate().to(URL);
((JavascriptExecutor) driver)
.executeScript("window.scrollTo(0, document.body.scrollHeight)");
}
@Test(priority=2)
public void scrollingToElement() {
driver.navigate().to(URL+"directory/companies/?trk=uno-reg-guest-home-companies-directory");
WebElement element = driver.findElement(By.linkText("Import/Export"));
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollIntoView();", element);
}
@Test(priority=3)
public void scrollingByCoordinates() {
driver.navigate().to(URL+"jobs2/directory/?trk=uno-reg-guest-home-jobs-directory");
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,500)");
}
@AfterClass
public void tearDown() {
driver.quit();
}
}
0 Comment(s)