Friday, January 14, 2011

Handling popup windows in selenium

Handling pop up windows in selenium is a good mechanism.
All you need to know is pop up window ID.
In general pop up windows are generated in a website with some javascript code .
That particular code is as follows.

window.open('url','windowname','properties');

or

window.open('url','','properties');

So in the first case we can be able to identify the pop up window in selenium.
Where as with second case we cannot be able to recognize the popup window.



Follow the below steps to recognize a pop up and move your control onto that pop up and do the necessary actions there and return back to main window.


package com.tests;

import com.thoughtworks.selenium.DefaultSelenium;

public class PopUpWindowDemo {

public static void main(String[] args) {
try {
DefaultSelenium selenium = new DefaultSelenium("localhost", 8888,"*iexplore", "http://localhost:8383");
selenium.start();
selenium.open("http://localhost:8383/testApplication/mainPage.jsp");

selenium.click("link=Click Me");
String[] winNames = selenium.getAllWindowNames();
for (String winName : winNames) {
if (!winName.contains("selenium")) {
selenium.waitForPopUp(winName, "30000");
selenium.selectWindow(winName);
selenium.windowFocus();
//Here u can write the steps related to pop up window....
//Close the pop up once all the manipulations in the pop up window done successfully...
//Move the cursor to the main Window using the selenium.selectWindow("null") or selenium.selectWindow("")
if(selenium.isElementPresent("//div[@id='popUpDiv']")){
System.out.println("U r successfully entered in pop up window");
System.out.println("Text in the pop up Window "+selenium.getText("//div[@id='popUpDiv']"));
if(selenium.isElementPresent("link=Close Me")){
selenium.click("link=Close Me");
}

}else{
System.out.println("U r not successfully entered in pop up window");
}
selenium.selectWindow("null");
selenium.windowFocus();
//Now the cursor is returned to the main window
//Do the operations on the main window...

}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}




7 comments:

  1. Thank U very much for the best example

    ReplyDelete
  2. Thank you very much, this is a good tip.
    Francois.

    ReplyDelete
  3. What is the front-end equivalent?

    ReplyDelete
  4. See, if this helps.

    Robotil is a simple library to press/release keyboard keys on remote machine.

    Download Link - http://www.codoid.com/products/view/2/27

    ReplyDelete
  5. See, if this helps.

    Robotil is a simple library to press/release keyboard keys on remote machine.

    Download Link - http://www.codoid.com/products/view/2/27

    ReplyDelete