i was trying to do with eventfiringwebdriver but not able to use it showing unwanted errors
EventFiringWebDriver EventFiringWebDriver = new EventFiringWebDriver(driver);
EventFiringWebDriver.executeScript
("document.querySelector('/html/body/begin:/div[1]/div[2]/div[2]/div)') ;
second method i was trying by javascript and actions
JavascriptExecutor jre = (JavascriptExecutor)driver;
jre.executeScript("window.scrollBy(0,1000)");
WebElement extension =
driver.findElement(By.xpath("/html/body/begin:/div[1]/div[2]/div[2]/div"));
Thread.sleep(2000);
jre.executeScript("argument[2000].scrollIntoView();", extension);
CodePudding user response:
To path the WebElement as argument for js script evaluation next syntax should be used:
WebElement extension =
driver.findElement(By.xpath("/html/body/begin:/div[1]/div[2]/div[2]/div"));
Thread.sleep(2000);
jre.executeScript("arguments[0].scrollIntoView();", extension);
argument[2000]
changed to arguments[0]
.
So, this command shouldn't throw errors any more.
Args passing to JavascriptExecutor.executeScript
This illustrates how to pass multiple args for evaluation, and why arguments[0]
should be used for the case when we pass a single argument.
int result = jre.executeScript("return (arguments[0] arguments[1] arguments[2])", 2, 5, 10);
System.out.println("Result: " result);
will print:
Result: 17
CodePudding user response:
You can use JS to scroll to specific location on the page (top/bottom) or you can scroll to element.
public void scrollToTop() {
jsExecutor.executeScript("window.scrollTo(0,0)");
}
public void scrollToBottom() {
jsExecutor.executeScript("window.scrollTo(0,document.body.scrollHeight)");
}
public void scrollToOffset(int x, int y) {
jsExecutor.executeScript("window.scrollTo(" x "," (y - 100) ")");
}
public void scrollToElement(WebElement webElement) {
scrollToOffset(webElement.getLocation().x, webElement.getLocation().y);
}
public void scrollToElement(By locator) {
scrollToTop();
scrollToElement(findElement(locator));
}