Wednesday, September 01, 2010

Switching Frame and Windows in WebDriver sample code

1> Switch to different Frames:
 List<WebElement> frameset = driver.findElements(By.tagName("frame"));  
 if(frameset.size()>0) {  
 for (WebElement framename : frameset){  
 System.out.println("frameid: " + framename.getAttribute("name"));  
 }  
 }  
 else System.out.println("can not find any frame in HTML");  

Notice when you set the frame index, it starts with 0 for the first frame:
 driver.switchTo().frame(0);  


2> Switch to different Windows:
 Set<string> handlers = driver.getWindowHandles();  
 if (driver.getWindowHandles().size()>= 1){  
 for(String handler : handlers){  
 driver.switchTo().window(handler);  
 if (driver.getCurrentUrl().contains("Popup")){  
 System.out.println("Get focus on Popup window");  
 break;  
 }  
 }  
 }  
 else System.out.println("No windows founded!");  


Writing a common function based you own app for switching will be more helpful for your Code Clean!

8 comments:

  1. This is helpful.. Thanks

    ReplyDelete
  2. Excellent thanks a million

    ReplyDelete
  3. Really nice:) Thanks from Poland:)

    ReplyDelete
  4. This helped me lot. Thanks

    ReplyDelete
  5. /*multiple iframes*/
    WebDriver driver = new FirefoxDriver();
    driver.get("http://timesofindia.indiatimes.com/");
    //will not work in FF
    //driver.switchTo().frame("mailroifrm12");
    WebElement ifr = driver.findElement(By.xpath("//iframe[@id='mailroifrm12']"));
    driver.switchTo().frame(ifr);
    Thread.sleep(3000L);
    driver.findElement(By.id("mathuserans2")).sendKeys("8");

    ReplyDelete