I opened a tab successfully then find a link on that page By Link text. Selenium could find it, click on it and open a new tab. Now, it is not able to find any element or perform any activity on the new tab.
it opened the new tab and went to that but is not able to do anything on that:
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Main {
public static void main(String[] args){
System.setProperty("webdriver.chrome.driver", "./Drivers/chromedriver.exe");
WebDriver Cdriver = new ChromeDriver();
Cdriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
Cdriver.get("URL");
Cdriver.findElement(By.id("username")).sendKeys("XYZ");
Cdriver.findElement(By.id("password")).sendKeys("XYZ@123");
Cdriver.findElement(By.id("loginbtn")).click();
Cdriver.findElement(By.linkText("Java(the text it had)")).click();
//next line is not working because it is on new page
Cdriver.findElement(By.linkText("Dashboard(another link on new page)")).click();
//Cdriver.quit();
}
}
CodePudding user response:
You need to use window handles.
Something like this:
String handles = driver.getWindowHandles();
Cdriver.switchTo().window(handles.get(1));
and then perform this action:
/next line is not working because it is on new page
Cdriver.findElement(By.linkText("Dashboard(another link on new page)")).click();
CodePudding user response:
You need to take your webdriver's control to new tab by using driver.switchTo().window(windowhandle)
Following is the sample code :-
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class WindowHandle_Demo {
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver","Path to the driver");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
// Load the website
driver.get("http://www.naukri.com/");
// It will return the parent window name as a String
String parent=driver.getWindowHandle();
Set<String>s=driver.getWindowHandles();
// Now iterate using Iterator
Iterator<String> I1= s.iterator();
while(I1.hasNext())
{
String child_window=I1.next();
if(!parent.equals(child_window))
{
driver.switchTo().window(child_window);
System.out.println(driver.switchTo().window(child_window).getTitle());
}
}
//switch to the parent window
driver.switchTo().window(parent);
}
}
following is the link for theoritical knowledge on this subject https://www.toolsqa.com/selenium-webdriver/window-handle-in-selenium/