Facebook

Course Name Start Date Time Duration Registration Link
No Training Programs Scheduled ClickHere to Contact
Please mail To sudhakar@qtpsudhakar.com to Register for any training

Thursday, September 28, 2017

Handling Dynamic Title Change Windows Using WebDriver

public class WorkingWithWindows {

 public static void main(String[] args) throws InterruptedException {
  // open new chrome window
  WebDriver driver = DriverFactory.getDriver("chrome");

  // specify page load
  driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);

  // specify element wait
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

  // maximize window
  driver.manage().window().maximize();

  // goto orange hrm login page
  driver.get("https://www.naukri.com/");

  // click on Login
  driver.findElement(By.xpath("//div[text()='Login']")).click();

  // click on facebook button
  driver.findElement(By.xpath("//span[text()='Facebook']")).click();

  String mWndHandle = driver.getWindowHandle();

  switchToWindowByTitle(driver, "Log in to Facebook | Facebook");

  // switchToWindowByChild(driver, By.id("email"));
  driver.findElement(By.id("email")).sendKeys("sudhakar@qtpsudhakar.com");

  driver.close(); // closes only current window

  driver.switchTo().window(mWndHandle);

  driver.quit(); // closes all windows opened in current session
 }

 public static void switchToWindowByTitle(WebDriver driver, String wndTitle) {
  /*
   * This method will switch to window using window title
   */

  // get set of windows
  Set strWndHandles = driver.getWindowHandles();

  // create a flag to print status
  boolean wndFound = false;

  // use for loop to switch every window
  for (String wndHandle : strWndHandles) {
   // switch to window using handler value
   driver.switchTo().window(wndHandle);

   // compare window title with expected
   if (driver.getTitle().equalsIgnoreCase(wndTitle)) {
    // break if title matches
    wndFound = true;
    break;
   }
  }

  // print status
  if (wndFound) {
   System.out.println("switched to " + wndTitle + " Window");
  } else {
   System.out.println("Window Not Found");
  }
 }

 public static void switchToWindowByChild(WebDriver driver, By cElmlocator) {
  /*
   * This method will switch to window using child element
   */

  // get set of windows
  Set strWndHandles = driver.getWindowHandles();

  // create a flag to print status
  boolean wndFound = false;

  // use for loop to switch every window
  for (String wndHandle : strWndHandles) {

   // switch to window using handler value
   driver.switchTo().window(wndHandle);

   // find expected element exist
   if (driver.findElements(cElmlocator).size() > 0) {
    // break if element exist
    wndFound = true;
    break;
   }
  }

  // print status
  if (wndFound) {
   System.out.println("switched to Window using child");
  } else {
   System.out.println("Window Not Found");
  }
 }
}
 

No comments :

Post a Comment