Close Window popup in Java (Selenium WebDriver)

7

I'm testing a website in java and need to close a window pop-up, the problem is that I already tried to use Selenium to close it and I could not.

Is there any simple way to date it using JAVA? You do not have to click anything, I just need to close it anyway.

I tried to close it like this:

String windowHandleJanelaInicial = driver.getWindowHandle();
        WebElement elementoQueAbreNovaJanela = driver.findElement(By.name("btnSimulateDK"));
        elementoQueAbreNovaJanela.click();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        Set<String> handles = driver.getWindowHandles();
        for(String windowHandle : handles) {        

            if( !windowHandle.equals(windowHandleJanelaInicial) ) {
                 driver.switchTo().window(windowHandle);
                driver.close();

            }
        }

        driver.switchTo().window(windowHandleJanelaInicial);
     }      

Complete code:

package BrowserWa;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.Select;

import java.io. * ;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class AbrindoBrowser {
     /**
      * @param args
      * @throws IOException
      */
     public static void main(String[]args)throws IOException {


          System.setProperty("webdriver.ie.driver", "C:/Users/paulo.roberto/Downloads/IEDriverServer_Win32_2.45.0/IEDriverServer.exe");
          DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
          caps.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
          WebDriver driver = new InternetExplorerDriver(caps);
          driver.get("http://PRAIASECA:8741/ativacao/index.jsp");


          //Dados para Login, localiza o campo e preenche com o valor
          driver.findElement(By.name("j_username")).sendKeys("5425321452");
          driver.findElement(By.name("j_password")).sendKeys("teste#123");
          driver.findElement(By.name("button")).click();
            driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

          driver.findElement(By.name("seller")).sendKeys("cos11");


          // ######## Tipos de Plano ################

        WebElement radioBtn = driver.findElement(By.xpath("/html/body/center/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/div/center/form/div/div[2]/div/div[2]/table/tbody/tr[7]/td[2]/table/tbody/tr[5]/td/input"));
                    radioBtn.click();                       

        WebElement radioBtn2 = driver.findElement(By.xpath("/html/body/center/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/div/center/form/div/div[2]/div/div[2]/table/tbody/tr[8]/td[2]/table/tbody/tr/td[2]/input"));
                        radioBtn2.click();

        WebElement radioBtn3 = driver.findElement(By.xpath("/html/body/center/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/div/center/form/div/div[2]/div/div[2]/table/tbody/tr[10]/td[2]/table/tbody/tr[4]/td/input"));
                        radioBtn3.click();


        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.findElement(By.xpath("/html/body/center/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/div/center/form/div/div[2]/div/div[1]/h2[2]/a")).click();
        driver.findElement(By.name("txtNome")).sendKeys("Paulo Roberto");
        driver.findElement(By.id("cpfField")).sendKeys(geraCPF());
        driver.findElement(By.xpath("/html/body/center/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/div/center/form/div/div[2]/div/div[3]/table/tbody[1]/tr[7]/td[2]/input")).sendKeys("04856384");
        driver.findElement(By.name("birthday")).sendKeys("02/04/1988");
        WebElement genero = driver.findElement(By.xpath("/html/body/center/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/div/center/form/div/div[2]/div/div[3]/table/tbody[1]/tr[9]/td[2]/input[1]"));
        genero.click();
        driver.findElement(By.name("customerMotherName")).sendKeys(sorteia());          
        Select estado_civil = new Select(driver.findElement(By.name("maritalStatus")));
        estado_civil.selectByIndex(1);
        Select ocupacao = new Select(driver.findElement(By.name("occupation")));
        ocupacao.selectByIndex(1);
        Select faixa_salarial = new Select(driver.findElement(By.name("wageRange")));
        faixa_salarial.selectByIndex(6);
        driver.findElement(By.xpath("/html/body/center/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/div/center/form/div/div[2]/div/div[3]/table/tbody[1]/tr[19]/td[2]/input")).sendKeys("11");
        driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
        driver.findElement(By.name("btnSimulateDK")).click();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.switchTo().window("[Pré-Análise de Crédito]");
        driver.close();

     }

     //Preenche o campo nome aleatóriamente
     public static String sorteia (){
          ArrayList<String> nome = new ArrayList<String>() ;

          nome.add("Alice");
          nome.add("Bruno");
          nome.add("Carlos");
          nome.add("Daniel");

          ArrayList<String> sobrenome = new ArrayList<String>() ;

          sobrenome.add("Duarte");
          sobrenome.add("Belavicqua");
          sobrenome.add("Zanetti");
          sobrenome.add("Cardoso");

          Collections.shuffle(nome);
          Collections.shuffle(sobrenome);
          return nome.get(0) + " " + sobrenome.get(0);
         }
     //Gera o CPF para preencher o campo cpf
    private static String calcDigVerif(String num) {    
            Integer primDig, segDig;    
            int soma = 0, peso = 10;    
            for (int i = 0; i < num.length(); i++)    
                    soma += Integer.parseInt(num.substring(i, i + 1)) * peso--;    

            if (soma % 11 == 0 | soma % 11 == 1)    
                primDig = new Integer(0);    
            else    
                primDig = new Integer(11 - (soma % 11));    

            soma = 0;    
            peso = 11;    
            for (int i = 0; i < num.length(); i++)    
                    soma += Integer.parseInt(num.substring(i, i + 1)) * peso--;    

            soma += primDig.intValue() * 2;    
            if (soma % 11 == 0 | soma % 11 == 1)    
                segDig = new Integer(0);    
            else    
                segDig = new Integer(11 - (soma % 11));    

            return primDig.toString() + segDig.toString();    
        }    

        public static String geraCPF() {    
            String iniciais = "";    
            Integer numero;    
            for (int i = 0; i < 9; i++) {    
                numero = new Integer((int) (Math.random() * 10));    
                iniciais += numero.toString();    
            }    
            return iniciais + calcDigVerif(iniciais);    
        }    

        public static boolean validaCPF(String cpf) {    
            if (cpf.length() != 11)    
                return false;    

            String numDig = cpf.substring(0, 9);    
            return calcDigVerif(numDig).equals(cpf.substring(9, 11));    
        } 



      }

Error displayed on console:

Exception in thread "main" org.openqa.selenium.NoSuchWindowException: No window found (WARNING: The server did not provide any stacktrace information)

HTML page that I am trying to close:

<html>
<head>
<title>
[Ativação] - Pré-Análise de Crédito
</title>
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Expires" content="0">
<script type="text/javascript" src="/ativacao/js/jquery_noConflict.js"></script>
</head>

<body>

<script type="text/javascript">
    J(window).bind("beforeunload", function() { 
        abrirSimulador();
    })
</script>

<center><!-- Início da Página --> <!-- Título da Página --> <br>
<table border="0" cellpadding="0" cellspacing="0" width="350">
    <tr>
        <td class="page-title">Pré-Análise de Crédito</td>
    </tr>
    <tr>
        <td class="page-subtitle">Mensagem de Informação</td>
    </tr>
</table>
<br>

<table border="0" cellpadding="0" cellspacing="0" width="300" >
    <tr>
        <td class="label" align="right">
            Código da operação: &nbsp;
        </td>
        <td class="text">
        002PjPr
        </td>
    </tr>
    <!-- OS 81138 - Inicio -->

    <tr>
        <td class="label" align="right">
            Pontos: &nbsp;
        </td>
        <td class="text">
        1,00
        </td>
    </tr>
    <tr>
        <td class="label" align="right">
            Limite:  &nbsp;
        </td>
        <td class="text">
        1500,00
        </td>
    </tr>

        <!-- OS 81138 - Fim -->

    <!-- OS Unificação Cadastral II -->
    <tr>
        <td class="label" align="right">
            Cliente America Movel:  &nbsp;
        </td>
        <td class="text">

            Sim


        </td>
    </tr>
    <!-- OS Unificação Cadastral II -->
    <tr>
        <td class="label" align="right">
            Resposta:  &nbsp;
        </td>
        <td class="text">
        Prosseguir
        </td>
    </tr>
    <tr>
        <td class="label" align="right">
            Justificativa:  &nbsp;
        </td>
        <td class="text">
            Limite calculado. Favor prosseguir com a venda
        </td>
    </tr>
    <tr>
        <td align="center" colspan="2">
            <input name="btnClose" type="button" class="button" value='OK' onclick="javascript:abrirSimulador();window.close();" />
        </td>
    </tr>
</table>

</center>
</body>
<script type="text/javascript">
function abrirSimulador(){
    window.opener.prosseguirAnaliseCredito = false;

    if(window.opener.scorePreAnalise){
        window.opener.prosseguirAnaliseCredito = true;
        window.opener.checkAssociateSimularPrecoPreAnalise(window.opener.simulatePopup);
        return;
    }
    window.opener.scorePreAnalise = false;

}
</script>
</html>

    
asked by anonymous 13.05.2015 / 21:32

1 answer

1

Try the following:

driver.switchTo().window("[handle da sua janela]");
driver.close();
// Ou um click no caminho do botão ok.

The method switchTo goes to the popup window. The method close closes the window current.

    
13.05.2015 / 22:58