0
votes

On trying to switch frame 2 via frame(webelement) method, I am getting error as

Element belongs to a different frame than the current one

My sample webpage has 2 frames name as FrameOne and FrameTwo with one textbox in each frame.. in 1st frame as name 1 and textbox in 2nd frame as name 2.

driver.navigate().to("file:///D:/Study%20material/8850OS_Code/Chapter%203/HTML/Frames.html");


/***********By id***********************/
driver.switchTo().frame(1);   //identify 2nd frame sucessfully
WebElement Textbox2=driver.findElement(By.name("2"));  //webelement in 2nd frame
Textbox2.sendKeys("Hi Vivek");
driver.switchTo().defaultContent();
driver.switchTo().frame(0).findElement(By.name("1")).sendKeys("Hello selenium");
driver.switchTo().defaultContent();
/***

/***********By WebElement***********************/
driver.switchTo().frame(Textbox2);  ---> this line throws error
Textbox2.sendKeys("Hi John");
driver.switchTo().defaultContent();
driver.switchTo().frame(0).findElement(By.name("1")).sendKeys("Hello selenium");

Please tell me how exactly this method works or where I am doing mistake.

2
What language is this? add the proper tag - Saeid
Could you share HTML code as well?? And specify what do you want to achieve actually?? - Saurabh Gaur
Saurabh , i want to switch to frame2 using its i.e frame2 previously located webelement. - Vivek

2 Answers

0
votes

You can not use textbox2 to switch to frame. The webelement overload for frame to locate iframe element like any other element.

WebElement iframe= driver.findElement(By.id(iframe));

driver.switchTo().frame(iframe);
0
votes

Try this code. It worked for me...

driver.navigate().to("file:///D:/Study%20material/8850OS_Code/Chapter%203/HTML/Frames.html");

/***********By id***********************/

WebElement ifrm1= driver.findElement(By.id("FrameOne")); 
WebElement ifrm2= driver.findElement(By.id("FrameTwo"));
driver.switchTo().frame(ifrm2);   //identify 2nd frame sucessfully
WebElement Textbox2=driver.findElement(By.name("2"));  //webelement in 2nd frame
Textbox2.sendKeys("Hi Vivek");
driver.switchTo().frame(ifrm1); // Switch Back to FrameOne
driver.findElement(By.name("1")).sendKeys("Hello selenium");


/***********By WebElement***********************/
driver.switchTo().frame(Textbox2);       

The Above line throws error as "TextBox2" is not a Frame Element

More info on frames can be found at https://www.seleniumeasy.com/selenium-tutorials/how-to-work-with-iframes-in-selenium-webdriver

Hope its helpful