How to Close Second Window in Java Selenium Example Program?

How to Close Second Window in Java Selenium Example Program?

package com.selenium.switchto;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Close2ndWindiw 
{
   WebDriver driver=new FirefoxDriver();
   @BeforeTest
   public void open()
   {
      driver.manage().window().maximize();
      driver.get("http://demoqa.com/frames-and-windows/");
      driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS);
   }
   @Test
   public void operation() throws InterruptedException
   {
      //String parent=driver.getWindowHandle();
      driver.findElement(By.xpath(".//*[@id='tabs-1']/div/p/a")).click();
      Thread.sleep(2000);
      Set<String> handles=driver.getWindowHandles();
      int count=0;
      for(String h:handles)
      {
         count++;
         System.out.println(count);
         if(count==1)
         {
            driver.switchTo().window(h);
            driver.close();	
         }
         else
         {
            continue;
         }
      }
      //driver.switchTo().window(parent);
      //driver.close();
   }
}

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment