Search code examples
iosseleniumappiumipados

Is there a way that Appium can focus to new window tab in Safari?


I'm doing my task to automate a specific website's performance by using Appium. I'm testing the iPadOS(iOS 14.x and above) and the website has a new tab feature when a button is clicked. Now, the problem is that when I tried to use getWindowHandles and sorts of that nothing happens. Here's my code:

String url = "https://demoqa.com/browser-windows"; driver.get(url);

    try {
        System.out.println(1321);
        Thread.sleep(5000);
        System.out.println(driver.getTitle()); 
        String currentHandle = driver.getWindowHandle(); 
        
        System.out.println(driver.findElement(By.xpath("//*[@id=\"tabButton\"]")).isDisplayed());
        
        driver.findElement(By.xpath("//*[@id=\"tabButton\"]")).click();
        System.out.println(driver.getTitle()); 
        Thread.sleep(5000);

        System.out.println(driver.getTitle());
        Thread.sleep(5000);
         //getting all the handles currently available
        Set<String> handles=driver.getWindowHandles();
        Thread.sleep(5000);
        System.out.println(handles.size());
        for(String actual: handles)
        {
            
         if(!actual.equalsIgnoreCase(currentHandle))
         {
             //switching to the opened tab
             driver.switchTo().window(actual); 
         }
        }

Output: 1321 ToolsQA true ToolsQA ToolsQA 1


Solution

  • The moment you do this :

    driver.findElement(By.xpath("//*[@id=\"tabButton\"]")).click();
    

    you need to switch to the new tab/window

    Code :

    ArrayList<String> handles = new ArrayList<String> (driver.getWindowHandles());
    System.out.println(driver.findElement(By.xpath("//*[@id=\"tabButton\"]")).isDisplayed());
    driver.findElement(By.xpath("//*[@id=\"tabButton\"]")).click();
    driver.switchTo().window(handles.get(1));
    System.out.println(driver.getTitle()); 
    

    Update 1 :

    driver.get("https://demoqa.com/browser-windows");
    WebDriverWait wait = new WebDriverWait(driver, 10);
    String currentHandle = driver.getWindowHandle();
    System.out.println(driver.findElement(By.xpath("//*[@id=\"tabButton\"]")).isDisplayed());
    driver.findElement(By.xpath("//*[@id=\"tabButton\"]")).click();
    Thread.sleep(2000);
    ArrayList<String> handles = new ArrayList<String> (driver.getWindowHandles());
    driver.switchTo().window(handles.get(1));
    System.out.println("Switched");
    System.out.println(wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("sampleHeading"))).getText());