Close Windows popup in Java (Selenium Webdriver)

Asked

Viewed 3,334 times

7

I am testing a site in java and need to close a Window pop-up, the problem is that I tried to use Selenium to close it and I could not.

Is there any simple way to close it using JAVA? You don’t need 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 shown in console:

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

HTML of the page I’m 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>

Window

  • I don’t quite understand your case. You’re using the Webdriver of Lenium? If yes the method close do what you want.

  • @Anthonyaccioly I am, but if I use driver.close(); It will close the popup and the main page and I am new to programming, I know you have the Switch, but I don’t know how to use it.

  • Paul, create a mvce with the code that is easier to help. The switch no mistake driver.switchTo().name("[nome da janela]");

  • @Anthonyaccioly I will create yes, regarding this code ai you passed, the eclipse claims that The method name() is Undefined for the type Webdriver.Targetlocator

  • I think I could explain a little better to make it easier to understand

  • @Otto Doubt is so simple that it is even difficult to explain my problem rsrsr I am not able to close this modal because I can’t find his xpath, since the site only runs in IE I have no way to use Firebug... Selenium cannot close the modal either with name, or with id, or with class, value, anything, since the beginning of the project it only finds elements with Xpath... I don’t know how to find xpath with IE or manually... Have any tool or any way to get the xpath of this button "OK"? or some way to close this modal?

  • It’s a modal or a popup?

  • If a pop up can close with driver.switchTo().window("[handle da sua janela]");&#xA;driver.close(); as @Anthonyaccioly said. If it’s a modal, make sure it’s an integral part of some other frame. Ae will have to switch to the frame and then search for it again. #odeioframes heheheheheh

Show 3 more comments

3 answers

2


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 current window.

1

People, and when this popup appears sometimes yes sometimes no. It is something frequent as you treat this problem ?

Following the suggestion of the colleague:

driver.switchTo().window("shoppush-prompt-close"); 
driver.close();

If POP UP is not displayed it closes the page.

1

Exception in thread "main" org.openqa.Selenium.Nosuchwindowexception: No window found (WARNING: The server Did not provide any stacktrace information)

This error message indicates that Selenium Webdriver did not locate the window, it may be because of the window title or something.

switchTo(). window(windowHandleJanelaInitial);

If I’m not mistaken, to go back to the initial window you can do so

driver.switchTo().window("");

And from what I’ve seen, the title of the page you want to close is not dynamic

<html>
<head>
<title>
[Ativação] - Pré-Análise de Crédito
</title>

So try this here:

// Pega a janela pelo titulo
    driver.switchTo().window("[Ativação] - Pré-Análise de Crédito");
//Fecha a janela selecionada
    driver.close();
//volta para a janela inicial
    driver.switchTo().window("");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.