Browser Functions

Handling Browser Functionality

Scroll Down:

/**
 * Scroll to the bottom of a page and sleep for 10 seconds
 * 
 */
public static void scrollDown() {
((JavascriptExecutor) SeleniumAction.getDriver())
.executeScript("scroll(0, 250)");
sleep(10); // Customized sleep method
}

Scroll Up:

/**
 * Scroll to the top of a page and sleep for 10 seconds
 * 
 */
public static void scrollUp() {
((JavascriptExecutor) SeleniumAction.getDriver())
.executeScript("scroll(250, 0)");
sleep(10); // Customized sleep method
}


Scroll Upto an Element:

/**
 * Scroll to an web element to make it display on screen 
 *  
 * @param element
 */
public static void scrollToAnElement(WebElement element) {
if (isElementExists(element)) {
((Locatable) element).getCoordinates().inViewPort();
sleep(5); // Customized sleep method
}

}

Maximize a web browser:
/**
* Maximize a browser window
*/
public void maximizeBrowserWindow(){
       driver.manage().window().maximize();
}

Refresh a browser:
/**
* Refresh a browser window
*/
//Method #1:
public void refreshBrowserWindow(){
       driver.navigate().refresh();
}

//Method #2:
public void refreshBrowserWindow(){
       driver.get(driver.getCurrentUrl());
}

// Method #3:
public void refreshBrowserWindow(){
      driver.navigate().to(driver.getCurrentUrl());  
}

//Method #4:
public void refreshBrowserWindow(WebDriver driver){
      Actions refreshAction = new Actions(driver);
      refreshAction.keyDown(Keys.CONTROL).sendKeys(Keys.F5).perform();
}

Handling an alert:
/**
 * Handling an alert dialog 
 * 
 *@param discard
 */
public void handleAlert(boolean discard){
     Alert alertHandler =    driver.switchTo().alert();
     if(discard){
          alertHandler.dismiss();
     } else {
           alertHandler.accept();
     }
}

Take a screenshot:

/**
 * Takes a screen shot and save with the given file name
 *  
 * @param fileName
 * @throws IOException
 */

public static void takeScreenshot(String fileName) throws IOException {
File screenshot = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
String dirPath = ScriptsExecuted.getRFTLogDirectory()
+ fileName
+ new SimpleDateFormat("MM-dd-yyy_HH:ss")
.format(new GregorianCalendar().getTime() + ".jpg");
FileUtils.moveFile(screenshot, new File(dirPath));
}

// For taking a screen shot on remote web driver, source

/**
  *  RemoteWebDriver does not implement the TakesScreenshot class
  *  if the driver does have the Capabilities to take a screenshot

  *  then Augmenter will add the TakesScreenshot methods to the instance
  */
public void myTest() throws Exception {
        WebDriver driver = new RemoteWebDriver(
                                new URL("http://localhost:4444/wd/hub"), 
                                DesiredCapabilities.firefox());
        
        driver.get("http://www.google.com");
        WebDriver augmentedDriver = new Augmenter().augment(driver);
        File screenshot = ((TakesScreenshot)augmentedDriver).
                            getScreenshotAs(OutputType.FILE);
}


Verification of an element existence:

/**
 * Method to verify whether desired web element is exists or not by handling
 * exceptions
 * 
 * @param element
 * @return
 */
public static boolean isElementExists(WebElement element) {
boolean result = false;
try {
if (element != null) {
result = element.isDisplayed();
}
} catch (NoSuchElementException noElementExecption) {
result = false;
} catch (StaleElementReferenceException staleElementException) {
return false;
}
return result;
}


Wait For page to load

void waitForLoad(WebDriver driver) {
    ExpectedCondition<Boolean> pageLoadCondition = new
        ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver driver) {
                return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
            }
        };
    WebDriverWait wait = new WebDriverWait(driver, 30);
    wait.until(pageLoadCondition);
}

Fluent Wait:
public static WebElement waitUntil(WebDriver driver, long waitUntilMinutes, long checkForEverySeconds, final By by) {
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(Duration.ofMinutes(waitUntilMinutes))
.pollingEvery(Duration.ofSeconds(checkForEverySeconds)).ignoring(NoSuchElementException.class);
return wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(by);
}
});
}

Validate Image Loaded properly

/**
  * Import statements, 
  */
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

public void validateInvalidImages() {
try {
invalidImageCount = 0;
List<WebElement> imagesList = driver.findElements(By.tagName("img"));
System.out.println("Total no. of images are " + imagesList.size());
for (WebElement imgElement : imagesList) {
if (imgElement != null) {
verifyimageActive(imgElement);
}
}
System.out.println("Total no. of invalid images are " + invalidImageCount);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}

}

public void verifyimageActive(WebElement imgElement) {
try {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(imgElement.getAttribute("src"));
HttpResponse response = client.execute(request);
// verifying response code he HttpStatus should be 200 if not,
// increment as invalid images count
if (response.getStatusLine().getStatusCode() != 200)
invalidImageCount++;
} catch (Exception e) {
e.printStackTrace();
}

}

3 comments:

  1. Superb work Fayaz, keep it up..!! Also please add Keyboard functionality stuff.. Thanks..!!

    ReplyDelete
  2. AN other way to wait for page load is

    driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
    WebDriverWait wait = new WebDriverWait(driver, 30);
    List linksize = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.tagName("a")));

    ReplyDelete
  3. Using java script also we can scroll into element
    ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", webElement);

    ReplyDelete