How to do Page Scroll Using JavascriptExecutor?

package seleniumwebdriverbestpractices;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

public class ScrollPage {

WebDriver driver;

@Test
public void scrollingPageTest() throws Throwable{
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\drivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
// driver.get("https://www.spicejet.com/");
driver.get("https://www.w3schools.com/");
driver.manage().window().maximize();


JavascriptExecutor js = (JavascriptExecutor)driver;

// Scroll Down
js.executeScript("window.scrollBy(0,1000)", "");
Thread.sleep(5000);

// Scroll Up
js.executeScript("window.scrollBy(0,-500)", "");
Thread.sleep(5000);

// Scroll to an element
WebElement element = driver.findElement(By.xpath("//div[@id='main']//a[text()='HTML Exercises']"));
js.executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(5000);

// Scroll to the bottom of the page
js.executeScript("window.scrollBy(0,document.body.scrollHeight)","");
Thread.sleep(5000);

driver.quit();

}

}

Comments

Post a Comment

Popular posts from this blog

Encoding and Decoding in Selenium using Base64 Class of Java

Parallel Execution In TestNG Framework Using ThreadLocal Concept

How to handle calendar or date picker using dynamic XPATH?