Friday, November 2, 2012

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!

1 comment:

  1. Hi,
    Thank you so much for posting this. I really appreciate your work. Keep it up. Great work!

    http://kosmiktechnologies.com/selenium/

    ReplyDelete