简体   繁体   中英

In Selenium java how to handle the pop up

I use selenium 2 and the browser version is IE 11. I face issue while handling with pop up.

Scenario 1:

driver.findElement(By.id("I create modal window")).click();
Set<String> windows = driver.getWindowHandles();
System.out.println(windows.size());

I get the output as 2 .

Scenario: 2 (with the same concept)

driver.findElement(By.id("I create pop up")).click();
Set<String> windows = driver.getWindowHandles();
System.out.println(windows.size());

I get the output as 1 .

I could not switch to the pop-up. Some times the pop-up response like not connected and moreover the size of the popup is way smaller than what it should be.

What would be the problem

Note : The element id's are not real one

From your question it looks like you wanted to switch to a pop - up.

Window handler is used to switch between browser windows.

Alert handler is used to switch between the pop - up messages.

If you wanted to accept/yes/ok the alert:

Alert alert = driver.switchTo().alert();
alert.accept();

If you wanted to dismiss/no/cancel the alert:

Alert alert = driver.switchTo().alert();
alert.dismiss();

You have to first check its window or alert.

Simply try to inspect element in that popup, if you are able to inspect elements in popup then its window so use switch to window command, if not then it is alert. So use switch to alert command (which provided in another answer)

There are different types of alerts and it should be handled differently as given below.

  1. Windows type: if your popup opened in a new window, you can handle it using get window handle and switch to window methods.

    driver.selectElement(By.id("I create modal window")).click(); Set<String> windows = driver.getWindowHandles(); System.out.println(windows.size()); for( String window : windows) driver.switchToWindow(window);

  2. Javascript alert: if the popup is javascript type. you can use switch to alert method.

    Alert alert = driver.switchTo().alert();

  3. DOM Element type: sometimes the popup is like DOM Element, created dynamically or hidden until popup. It can be handled using find elemeent method.

    driver.findElement(locator).Click();

I haven't fix my problem, but I found interesting things : when i open a popup, it is not connected to the current session if i open my web site with Selenium, even if don't ask Selenium to open my popup but i do it my self. If id do :

driver.quit()

the Main window will be close but not the popup

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM