Popular Usage of Javascript for Automation

Scroll Element

public static void scrollElementIntoView(WebDriver driver, WebElement element)
{
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript(“arguments[0].scrollIntoView()”, element);
}

public static void scrollToTopOfElement(WebDriver driver, WebElement element)
{
int offset = element.getSize().getHeight() * (-1);
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript(“window.scrollBy(0,” + offset + “)”, “”);
}

Scroll screen by offset

//Scroll down:
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript(“window.scrollBy(0,250)”, “”);

// Scroll up:
jse.executeScript(“window.scrollBy(0,-250)”, “”);
//or just
jse.executeScript(“scroll(0, -250);”);

Wait for page to load. Note: no need to use this method for driver.get(url). You can use this when certain user action causes page to reload or repaint.

public static void waitForPageToLoad(WebDriver driver) {
ExpectedCondition expectation = new ExpectedCondition() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript(“return document.readyState”).equals(“complete”);
}
};

Wait wait = new WebDriverWait(driver,1000);
try {
wait.until(expectation);
} catch(Throwable error) {
System.out.println(“Timeout waiting for Page Load Request to complete.”);
}
}