Sunday, January 8, 2012

Webdriver - How to handle Modal pop-up.

Webdriver - How to handle IE modal pop-up.

Issue Resolved for IE


Before we start understanding the model-popup, lets understand different pop-ups available on the browser. As per my understanding pop-ups are classified into.

1. HTML pop-up
2. JavaScrip pop-up
3. Win32 pop-up
4. Modal pop-up
5. File upload pop-up
6. File download pop-up

HTML pop-up - These are constructed using HTML, so it can be easily handled by Id or xPath. If you are able to locate the object using IE developer tool bar or Firebug then it is HTML popup.

JavaScrip pop-up - This popup is generated by "alert" statement, it can be handled using Webdriver or Java-script.
Alert Java Doc

Win32 pop-up - This popup is generated by windows, I came came across one popup of this kind. Webdriver can't handle it. Need to relay on Auto it or Java Robot class.

Modal pop-up - This is very specific to IE, Microsoft defined it as

When Windows Internet Explorer opens a window from a modal or modeless HTML dialog box by using the showModalDialog method or by using the showModelessDialog method, Internet Explorer uses Component Object Model (COM) to create a new instance of the window. Typically, the window is opened by using the first instance of an existing Internet Explorer process. When Internet Explorer opens the window in a new process, all the memory cookies are no longer available, including the session ID. This process is different from the process that Internet Explorer uses to open a new window by using the open method.
http://msdn.microsoft.com/en-us/library/ms536759(VS.85).aspx

MSDN blog on Modal dialog

When user select Model popup, parent window is blocked waiting for the return value from the popup window. You will be not able to see the view source of the page, need to close the popup then only the parent window is activated.

How to get object properties of the model-popup? Copy the popup URL and open in a new TAB, then it will display in normal window format, where you can use IE Dev Toolbar or FireBug to capture properties.

Modal window popup activation client code looks like this

var val = window.showModalDialog(url + '?Ids=' + Id, null, 'dialogHeight: 600px; dialogWidth: 850px,dialogTop: 190px;  dialogLeft: 120px; edge: Raised; center: Yes;help: No; resizable: No; status: No;');

As per Webdriver team this issue is fixed on IE in 2.16.0, but still it is not working.

Workaround provided in Ruby using Fork, but there is no corresponding Fork command in Java.

As per my understanding, currently there is no solution. Even AutoIt can't handle popup objects because they belong to HTML not the windows, it can hardly handle the Window title. How to handle? This is blocking my major test cases.

1. Change the Modal popup design.
If you can influence and convince the the team, covert the model-popup into HTML Modal Popup, so that it can be easily handled in other browsers too.
2. Manipulating the page DOM.
3. Java Robot class
When browser open modal popup opened, focus automatically set on the popup. Now assume you don't have mouse input device, handle the elements using "TAB" "Enter" "Space". Robot class also perform the same events as stated above. Given delay of at-least 500ms in between two events, otherwise there are chances of missing the events.


      //To understand the concept, handle the pop-up without mouse
      //Same thing is performed through robot API
      //Text that need to be typed, character by character
      //Issue - If anyone changes the window focus, keys are lost
      Wait(5000); // Wait for model pop, as Webdriver don't handle need hard stop
        int keyInput[] =
        {
          KeyEvent.VK_S, KeyEvent.VK_E, KeyEvent.VK_L, KeyEvent.VK_E,
          KeyEvent.VK_N, KeyEvent.VK_I, KeyEvent.VK_U, KeyEvent.VK_M,
        };   
       
        Robot robot = new Robot();
       
        robot.keyPress(KeyEvent.VK_TAB);
        robot.keyPress(KeyEvent.VK_TAB);
       

        for (int i = 0; i < keyInput.length; i++)
        {    
          robot.keyPress(keyInput[i]);
          robot.delay(100);    
        }  

        robot.delay(1000); 
        robot.keyPress(KeyEvent.VK_TAB);
        robot.delay(1000);
        robot.keyPress(KeyEvent.VK_TAB);
        robot.delay(1000);
        robot.keyPress(KeyEvent.VK_TAB);

        robot.delay(1000);
        robot.keyPress(KeyEvent.VK_ENTER); // Save Btn

File upload pop-up
If you are using file upload control SendKeys work perfectly fine on IE, else you need to relay on AutoIT.

File download pop-up
Need to depend on AutoIt, it works good with windows objects.

---

77 comments:

  1. Hi Bharat,

    as per selenium documentation "Selenium does NOT support JavaScript alerts that are generated in a page's onload() event handler. In this case a visible dialog WILL be generated and Selenium will hang until someone manually clicks OK."

    can we handle those alerts now?

    ReplyDelete
  2. It can handle JavaScript alerts, I am not sure about Onload event. Use AutoitV3 or Robot class.

    ReplyDelete
  3. Hi Bharat,
    Thanks for this article.
    I am facing somewhat different issue. I have this line of code in my ASP page:

    szOrg = window.showModalDialog("LOGINFORM.ASP?Task=NewLogin", window, "dialogHeight:<%=220 + lDialogHeightOffset%>px; dialogWidth:230px; center:yes; rersizeable:no; scroll:no; status:no;");

    Which opens a new login window.

    Using, selenium Webdriver, I want to send uname and password to this window. How do i do it?
    My selenium code (in C#) looks like this:

    driver = new InternetExplorerDriver();
    baseURL = "http://atlanta/wl30"; //my application link

    driver.FindElement(By.Id("MenuItem_1")).Click();
    driver.FindElement(By.Id("MenuItem_2")).Click();

    Upon clicking this, it shows loginform.asp and that is where I want to pass the values.
    I tried doing
    driver.SwitchTo().Window("frmUserLogin");
    but it did not work.

    Do you have any idea how this can be done?
    Thanks in advance,
    Anuja

    ReplyDelete
  4. Hello Anuja,

    This is not correct driver.SwitchTo().Window("frmUserLogin");
    You need to switch window handle id


    I hope following example will help you to solve the issue.

    driver.findElement(By.id("ctl00_CphePurchase_lnkCategory")).click(); //Open Modal dialog
    Wait(9000); // Wait for popup. Need to optimize the code
    driver.getWindowHandles();
    Set availableWindows = driver.getWindowHandles();
    Print("Handle Size:" +availableWindows.size());
    int Windows = 2;
    if (availableWindows.size()==Windows) {

    // For loop for modal popup
    for (String windowId : availableWindows) {
    if ("Select Product & Category".equals(driver.switchTo().window(windowId).getTitle())){
    Print("Modal popup:"+driver.getTitle());
    driver.findElement(By.id("chk_PASID_94135508")).click();
    driver.findElement(By.id("btnDown")).click();
    break; // Task completed, just come out
    }
    }

    // For loop back to parent
    for (String windowId : availableWindows) {
    if (("Requisition".equals(driver.switchTo().window(windowId).getTitle()))){
    Print("Parent Window:"+driver.getTitle());
    break; // Task completed, just come out
    }
    }
    }
    else
    {
    Print("No popups found"); //Implement assertion
    }

    ReplyDelete
  5. Anuja,

    If you want to eliminate for loops, use this code

    driver.findElement(By.id("ctl00_CphePurchase_invServItem$3$0$iconLIComment")).click(); //Open Comment dialog
    Print("Start of modal popupcode");
    Print("Comment and Attachments modal popup");
    try
    {
    Set availableWindows = driver.getWindowHandles();
    Print("Handle Size:" +availableWindows.size());
    long timeoutEnd = System.currentTimeMillis()+30000;
    while (availableWindows.size() == 1 )
    {
    Thread.sleep(100);
    availableWindows = driver.getWindowHandles();
    if(System.currentTimeMillis() > timeoutEnd)
    {
    Print("Comments and Attachments Modal popup TimeOut Occured");
    throw new WebDriverException();
    }
    }
    Print("Handle Size:" +availableWindows.size());
    //Wait(9000); // Wait for page to load
    //Retreive all the window handles into variables
    String WindowIDparent= null, WindowIDModal = null;
    int counter = 1;
    for (String windowId : availableWindows) {
    if (counter == 1){
    Print(Integer.toString(counter)+" " + windowId);
    WindowIDparent = windowId;
    }
    if (counter == 2){
    Print(Integer.toString(counter)+" " + windowId);
    WindowIDModal = windowId;
    }
    counter++;
    }
    //Navigate to Modal Popup
    driver.switchTo().window(WindowIDModal);
    Print(driver.getTitle());
    driver.findElement(By.id("txtCommentText")).sendKeys("Selenium");
    driver.findElement(By.id("btnSave")).click();
    Wait(7000);
    driver.close();

    //Navigate to Parent window
    driver.switchTo().window(WindowIDparent);
    Wait(4000);
    Print("In the Parent");
    Wait(2000);

    }
    catch (WebDriverException e)
    {
    e.printStackTrace();
    Print("Comments and Attachments Modal popup - Issue in the popup");
    xKillIEs(); //driver.quit() not working with modal dialog
    }

    ReplyDelete
    Replies
    1. Thanks for such a quick reply. But when I tried to get the window handles, I got this compilation error:

      OpenQA.Selenium.IWebDriver' does not contain a definition for 'getWindowHandles'

      Is there something I am missing?

      Delete
  6. Replies
    1. Not sure how to find that.
      But I downloaded selenium-dotnet-2.20.0

      Delete
    2. ok you are using .Net, try below code.

      // This would use the @Test annotation in JUnit4 or TestNG
      [Test]
      public void ModalTest()
      {
      IWebDriver driver = new InternetExplorerDriver();
      driver.Url = "https://developer.mozilla.org/samples/domref/showModalDialog.html";

      // Get current window handle for switching back after closing the dialog
      string originalHandle = driver.CurrentWindowHandle;
      IWebElement element = driver.FindElement(By.TagName("input"));
      element.Click();

      // Wait for the number of window handles to be greater than 1, or a timeout.
      // In Java, this would be something like the following:
      //
      // long timeoutEnd = System.currentTimeMillis() + 5000;
      // while (driver.getWindowHandles().size() == 1 && System.currentTimeMillis() < timeoutEnd) {
      // Thread.sleep(100);
      // }
      DateTime timeoutEnd = DateTime.Now.Add(TimeSpan.FromSeconds(5));
      while (driver.WindowHandles.Count == 1 && DateTime.Now < timeoutEnd)
      {
      System.Threading.Thread.Sleep(100);
      }

      // Loop through all window handles, finding the first one that isn't
      // the original window handle, and switching to it. Note that in Java,
      // this would be something like:
      //
      // for (string handle : driver.getWindowHandles()) {
      // if (!handle.equals(originalHandle)) {
      // driver.switchTo().window(handle);
      // break;
      // }
      // }
      foreach (string handle in driver.WindowHandles)
      {
      if (handle != originalHandle)
      {
      driver.SwitchTo().Window(handle);
      break;
      }
      }

      // If we've gotten to this point without switching windows, this will
      // throw an exception.
      string textBoxValue = driver.FindElement(By.Id("foo")).GetAttribute("value");

      // This is an NUnit test case, so we'll Assert here. Java would be similar
      // using either JUnit or TestNG.
      Assert.AreEqual("Dialog value...", textBoxValue);

      // Close the popup, and switch back to the original window.
      driver.Close();
      driver.SwitchTo().Window(originalHandle);

      // This page throws a JavaScript alert() when the dialog is closed,
      // so handle that dialog.
      driver.SwitchTo().Alert().Accept();

      // Quit the driver
      driver.Quit();
      }

      Delete
  7. Cool.. This worked exactly as needed :) :)
    Thanks a ton!! :) :) :) :)

    ReplyDelete
  8. I have similar issue, described at:
    http://code.google.com/p/selenium/issues/detail?id=3615
    Comment#1
    Any info. on the behavior as described in this issue.
    Wondering why some times it works and some times fails

    ReplyDelete
    Replies
    1. It is not advisable to use wait and Set windows = driver.getWindowHandles();
      Need to implement pooling logic

      Set availableWindows = driver.getWindowHandles();
      Print("Handle Size:" +availableWindows.size());
      long timeoutEnd = System.currentTimeMillis()+30000;
      while (availableWindows.size() == 1 )
      {
      Thread.sleep(100);
      availableWindows = driver.getWindowHandles();
      if(System.currentTimeMillis() > timeoutEnd)
      {
      Print("Comments and Attachments Modal popup TimeOut Occured");
      throw new WebDriverException();
      }

      For more details read the comments of IE driver project lead
      http://code.google.com/p/selenium/issues/detail?id=284#c76

      Delete
  9. Hi
    I have tried pooling logic but its hangs at getWindowHandles() and upon closing the modal pop up, next lines of code are executed.

    ReplyDelete
    Replies
    1. ok. I have handled complex modal popup's in IE, but not faced this kind of problem.

      Post your issue along with page and modal dialog html, so that Jim(IE driver lead) can solve the problem.

      http://code.google.com/p/selenium/issues/detail?id=284

      Delete
  10. Hi barath,

    nice and very useful blog.i am facing some problem in window's popup,please help to solve these popup's.when i will perform click command,new window will get open with the particular url and some action will cted to the performed on that window and it will get affeparent window,example like there is one option officelist,if i click on that a new window will open and i will select officelist and it will get affected to parent window.whenever i will run from the script,testcases is getting fail because of windows popup.

    ReplyDelete
    Replies
    1. What error are you getting?
      When there are multiple windows, windows handle size?

      Delete
    2. Could you please tell me how to store alert message for this url http://demo.cropin.in .By entering anything on username and password field,it will give a message “Invalid user”.I want to store this message and print it in a console but not use Threadsleep(). means that program wait for popup and when popup is come then value is coming the console. Problem is waiting time may be 10 sec to 30 sec, its depand the net speed. Please send the solution for my id kapilkumarvarshney.it@gmail.com

      Delete
  11. Hi,

    My application runs on IE only. In my application when i select a specific radio button then a popup window is opens. The popup window opened is not having right click enabled and any type of IE developer tool.
    How can i have the control over popup window and identify the element properties.

    Thanks,
    Mukesh
    mrawat213@gmail.com

    ReplyDelete
    Replies
    1. Copy the Dialog URL and pate it in new TAB, then you can capture the object properties using IE developer tool bar.

      Delete
  12. In my application "modal frame dialog window" opens after clicking on radio button. I am using getWindowHandles() function but it doesn't gives the dialog window handle. It only gives the handle of parent window.

    I am using code:-

    String currentWindowHandle=objDriver.getWindowHandle();
    objWebElement = objDriver.findElement(By.id(strTarget1));
    objWebElement.click();
    String htmlModalWindowHandle= null ;
    Wait_Sec("120");
    Set handles = objDriver.getWindowHandles();
    for(String windowHandle:handles)
    {
    System.out.println(windowHandle);
    if (!windowHandle.equals(currentWindowHandle)){
    htmlModalWindowHandle=windowHandle;
    System.out.println(htmlModalWindowHandle);
    }
    }
    objDriver.switchTo().window(htmlModalWindowHandle);

    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    It shows "java.lang.NullPointerException" error

    ReplyDelete
    Replies
    1. Are you getting handle size 2?
      Set availableWindows = driver.getWindowHandles();
      Print("Handle Size:" +availableWindows.size());

      Don't use hard wait, use pooling mechanism. Read above post for better understanding.

      Delete
  13. No, I am getting handle size=1 using pooling mechanism.

    ReplyDelete
    Replies
    1. Some thing is wrong in your code. You need to get handle size >1, that is the reason you are getting null pointer exception.

      Delete
  14. i am using the same code in some other app its working not in my app.

    ReplyDelete
    Replies
    1. Log a defect with entire page and modal dialog html

      Delete
  15. Please check my problem in google groups. Below is the link of my issue

    https://groups.google.com/forum/?hl=en&fromgroups#!topic/webdriver/n_p-7sXatco

    ReplyDelete
    Replies
    1. Have you seen the comments of Jim(Project lead of IE driver)

      Two questions: First, what version of the Selenium library are you using? There were changes in the last few versions in this area, and if you're using a sufficiently older version, you might have problems. Second, what happens if you delay your call to getWindowHandles()? Since mouse clicks are asynchronous, you'll need to wait for a bit to make sure the popup window appears. For now, try a simple Thread.sleep(). If that solves the problem, you'll want to refactor the code to use some sort of wait routine (like a WebDriverWait).

      --Jim

      Delete
    2. Webdriver version ?
      IE version ?
      I have handled complex modal dialog, but never faced with the issues of having only one handles. If handle is 1, ur webdriver code might be wrong or webdriver is not able to recognize the new window.

      Can you send me the HTML code pertaining to this button, how it is getting invoked.

      Delete
  16. WebDriver 2.20 and IE8

    Html code is:

    input id="workBench_main_IntegratedWorkViewSearch_IwvFilter_ctlAssignedBy_rdoAssignedByResources" type="radio" onclick="lookupAssignedByResource();" value="rdoAssignedByResources" name="ctl00$workBench$main$IntegratedWorkViewSearch$IwvFilter$ctlAssignedBy$assignedByGroup"

    label for="workBench_main_IntegratedWorkViewSearch_IwvFilter_ctlAssignedBy_rdoAssignedByResources">Resource(s)</label

    img align="absbottom" title="Assigned By Resources" onclick="lookupAssignedByResource();" style="cursor:pointer;" src="https://staticprogressive-dev.mymitchell.com/static/images/icon_lookup.gif"



    JavaScript for this:

    // Call resource lookup for assigned by Resource(s). 'N' indicates that this is not for group. In case of group
    // this value need to be send as 'Y'.
    lookupAssignedByResource = function () {
    $('input[id$=rdoAssignedByResources]', $('#divAssignedBy')).attr('checked', true);
    var headerText = "Assigned By Resources";
    var ctlResourceID = $('input[id$=hdnAssignedById]', $('#tdHiddenContainer'));
    var ctlResourceName = $('input[id$=hdnAssignedByName]', $('#tdHiddenContainer'));
    var ctlContainerId = CTL_ASSIGNEDBYCONTAINER_PANEL;
    GetResourceLookupParams('N');
    lookupResourceNames(oResourceLookupParams, ctlResourceName, ctlResourceID);
    if (ctlResourceName.value != undefined && ctlResourceName.value != '') {
    FormatDisplayLookup(ctlResourceID, ctlResourceName);
    $('input[id$=hdnAssignedById]', $('#tdHiddenContainer')).val(ctlResourceID.value);
    $('input[id$=hdnAssignedByName]', $('#tdHiddenContainer')).val(ctlResourceName.value);
    BindLookup(LookupType.AssignedBy);
    }
    }

    ReplyDelete
    Replies
    1. No idea.
      Only Jim can help you.
      Are you able to locate following statement in your page HTML
      var retval = window.showModalDialog(dialog, varArgIn, varOptions);
      http://msdn.microsoft.com/en-us/library/ms536759(VS.85).aspx

      Delete
  17. Hi Bharath,

    Please see my problem
    https://groups.google.com/forum/?hl=en&fromgroups#!topic/webdriver/4n68vqEl30Q

    Can u help me out regarding the same????

    ReplyDelete
    Replies
    1. I didn't come across this situation, use robot class to close the dialog.

      Delete
    2. Hello Manoj,
      Use AutoItv3 to detect the popup and close it.

      Delete
  18. Hi Bharath,

    let me know how to locate a modal pop whose id is auto generated , the number of times the pop occurs its comes with new ID.

    Thanks & Regards,
    Ajay

    ReplyDelete
    Replies
    1. getWindowHandles() method will retrieve the handle ids, every new popup will have different id's.

      Delete
  19. hi Bharath,

    I want to save image when mouse right click even is done then menu appears and i click on save image as and i want to give path and image will save at that location.....

    here is my code:
    mhover.contextClick(driver.findElement(By.xpath("/html/body/a/table/tbody/tr/td/form/a[2]/table[2]/tbody/tr[4]/td/table/tbody/tr/td[2]/img")));
    mhover.perform();
    Thread.sleep(1000);
    mhover.moveToElement(driver.findElement(By.partialLinkText("Save Image As..."))).click();

    ReplyDelete
  20. Hi Bharath

    I want to save image by mouse right click and then select option save image as and also give location where i want to save my image

    code.....

    mhover.contextClick(driver.findElement(By.xpath("/html/body/a/table/tbody/tr/td/form/a[2]/table[2]/tbody/tr[4]/td/table/tbody/tr/td[2]/img")));
    mhover.perform();
    Thread.sleep(1000);
    mhover.moveToElement(driver.findElement(By.partialLinkText("Save Image As..."))).click();

    ReplyDelete
    Replies
    1. Try using Robot class and Autoit v3
      http://codedrop.blogspot.in/2011/03/control-mouse-using-robot-class.html

      Delete
  21. can any one help me how to handle panel

    ReplyDelete
  22. Hi Bharath,

    Your code works perfect. In my scenario I'm having multiple popup ie., driver.getWindowHandles().size() == 3.I need to store first popup and second popup, so that after finishing task with second popup I can able to navigate to first popup then to the main window.

    Can you suggest me a solution.

    ReplyDelete
    Replies
    1. Copy the handles into a variable and use accordingly, below sample logic can hep you to build for 3 popups.

      Set availableWindows = driver.getWindowHandles();
      Print("Handle Size:" +availableWindows.size());
      long timeoutEnd = System.currentTimeMillis()+30000;
      while (availableWindows.size() == 1 )
      {
      Thread.sleep(100);
      availableWindows = driver.getWindowHandles();
      if(System.currentTimeMillis() > timeoutEnd)
      {
      Print("Category popup TimeOut Occured");
      throw new WebDriverException();
      }
      }
      Print("Handle Size:" +availableWindows.size());
      Wait(9000); // Wait for page to load
      //Retreive all the window handles into variables
      String WindowIDparent= null, WindowIDModal = null;
      int counter = 1;
      for (String windowId : availableWindows) {
      if (counter == 1){
      String Windowname = driver.switchTo().window(windowId).getTitle();
      //Print(Integer.toString(counter)+" " + windowId);
      Print(Integer.toString(counter)+" " + windowId +" : "+ Windowname);
      if(Windowname.matches(ParentWindowName)==true){
      WindowIDparent = windowId;
      Print("WindowIDparent assigned as :" +WindowIDparent);
      }else{
      WindowIDModal = windowId;
      Print("WindowIDModal assigned as :" +WindowIDModal);
      }

      }
      if (counter == 2){
      String Windowname = driver.switchTo().window(windowId).getTitle();
      //Print(Integer.toString(counter)+" " + windowId);
      Print(Integer.toString(counter)+" " + windowId +" : "+ Windowname);
      if(Windowname.matches(ParentWindowName)==true){
      WindowIDparent = windowId;
      Print("WindowIDparent assigned as :" +WindowIDparent);
      }else{
      WindowIDModal = windowId;
      Print("WindowIDModal assigned as :" +WindowIDModal);
      }

      }
      counter++;
      }
      //Navigate to Modal Popup
      driver.switchTo().window(WindowIDModal);
      Wait(5000);
      Print(driver.getTitle());
      driver.findElement(By.id("vmmComponent_txtBCompanyName")).sendKeys(SupplierName);
      driver.findElement(By.id("vmmComponent_btnSearch")).click();
      Wait(10000);
      Print("btn click done");
      driver.findElement(By.id("vmmComponent_grdSuppliers$3$0$checkId")).click();
      Print("Chkbox clicked");
      Wait(4000);
      driver.findElement(By.id("btnVMMClose")).click();
      Print("Select & Close Btn");
      Wait(7000);
      driver.close();

      //Navigate to Parent window
      driver.switchTo().window(WindowIDparent);
      Wait(4000);
      Print("In the Parent");
      Wait(2000);

      Delete
    2. Thanks for your valuable replay.
      In my application, I do not have either window id or window name. Window title remains similar to all the windows. So, I use iterator.next(); for handle navigation.
      It doesn't seem a good solution, since it fails most times.

      My flow in detail:
      Clicking a link from main window invokes first popup. Then clicking a link in first popup invokes second popup.After finishing with second popup return back to first popup then the main window.

      Delete
  23. Hi Bharath,
    I really liked your post..my issue is there is a link in application and as soon as I click on link a modelpopup comes and I have to click on yes.

    I have this code :-driver.FindElement(By.Id("ctl00_ContentPlaceHolder1_grdCaseOpen_ctl03_lnkApprove")).Click();

    I am using 2.24.1 webdriver and .NET.

    But as soon as I am clicking on link I am getting this error:-
    System.InvalidOperationException : Modal dialog present
    Build info: version: '2.24.1', revision: '17205', time: '2012-06-19 17:28:14'
    System info: os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.7.0_02'
    Driver info: driver.version: FirefoxDriver
    Session ID: 9b4d2ea6-b180-4c4e-bc04-a64c6cee7d7f (UnexpectedAlertOpen)

    I am seeing that lots of people are having trouble because of this..any help work around if you can suggest..?

    I tried this too :-((IJavaScriptExecutor)Initializer.driver).ExecuteScript("document.getElementById('ctl00_ContentPlaceHolder1_grdCaseOpen_ctl03_lnkApprove').click();");
    But popup comes and goes in 1 second ..and no action takes in popup.
    Thanks
    PJ

    ReplyDelete
  24. Hi Bharath,

    To handling authentication in Selenium WebDriver, many people seems to have used AutoIT. Personally I don't have anything against it, but I don't want to rely on installing the tool on all machines. If we use Selenium Grid , I am not sure how AutoIT will behave if we run multiple parallel test.

    While looking at an alternatives, I came across Robot class, which generates mouse and key events. This can be utilized to type the user name and password and Press Enter (Simulate OK button).

    The Robot class perfectly work in IE. Below is the code. Unfortunately, the below code dosen’t work in Firefox and Chrome browser. Can you please help/suggest me in this regard?

    import java.awt.Robot;
    import java.awt.event.KeyEvent;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.ie.InternetExplorerDriver;

    public class Robot_2 {


    public static void main(String[] args) throws Throwable {

    WebDriver driver = new InternetExplorerDriver();
    driver.get("http://testsite.com");

    Robot robot = new Robot();
    robot.delay(3000);

    try{

    //Will type userid as test
    robot.keyPress(KeyEvent.VK_T);
    robot.keyPress(KeyEvent.VK_E);
    robot.keyPress(KeyEvent.VK_S);
    robot.keyPress(KeyEvent.VK_T);

    }catch(Exception AWTException){
    System.out.println("Exception " + AWTException.getMessage());
    }

    }

    }

    ReplyDelete
    Replies
    1. What happens in chrome and firefox browsers?
      For AutoIt it is not required to install the software in all the system, code get compiled and a small exe file is generated, just need to invoke it, reliability is good.

      Delete
  25. Hi,

    On Windows file upload popup, I'm able use Robot class to generate key events for pasting and closing the modal dialog(CTRL V ENTER) but it only works on Firefox. In IE, once the file upload dialog pops up, the text is not being pasted in the highlighted area.

    Any ideas?

    My code is something like this:

    // copy the image path into the clipboard.
    String fileName = TestUtil.loadSCMProperties().getProperty("UploadFile");
    String filePath = System.getProperty("user.dir") + fileName;
    System.out.println("clipboard:"+filePath);
    setClipboardData(filePath);

    //native key strokes for CTRL, V and ENTER keys (paste the path into the edit box which is in focus)
    try {
    robot = new Robot();
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.delay(500);
    robot.keyPress(KeyEvent.VK_V);
    robot.delay(500);
    robot.keyRelease(KeyEvent.VK_V);
    robot.delay(500);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.delay(500);
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.delay(500);
    robot.keyRelease(KeyEvent.VK_ENTER);
    robot.delay(500);
    } catch (Exception e) {
    Reporter.log(e.getStackTrace().toString());
    }

    ReplyDelete
  26. Hi Bharath,
    I have tried the below piece of code to do mouse operations on my application.

    I have to put mouse hand icon over the menu to get the list of submenus , once i do mouse over on that menu it displys set of submenus as a drodown(dynamic functionality) among those submenus we have to click on specific link

    for this i have written the following piece of code.
    package Test;
    import org.openqa.selenium.By;
    //import org.openqa.selenium.HasInputDevices;
    //import org.openqa.selenium.Mouse;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebDriverBackedSelenium;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    //import org.openqa.selenium.interactions.Actions;
    //import org.openqa.selenium.internal.Locatable;
    //import org.openqa.selenium.interactions.Actions;
    //import org.testng.annotations.BeforeClass;
    import org.testng.annotations.Test;

    public class Case{


    private WebElement Uname = null;
    private WebElement Pwd = null;
    private WebElement Login = null;
    private WebElement Aries_Select = null;
    private WebElement Aries_Select1 = null;
    private WebDriver d1=null;
    //private Actions builder = null;

    /*@BeforeClass

    public void setup()
    {
    d1=new FirefoxDriver();
    builder = new Actions(d1);
    }*/


    @Test
    public void Testing() throws InterruptedException
    {
    d1=new FirefoxDriver();
    d1.get("https://ecentertest.hmsy.com/shr/Controller ");
    Uname = d1.findElement(By.name("USER"));
    Pwd = d1.findElement(By.name("PASSWORD"));
    Login = d1.findElement(By.xpath("html/body/form/table/tbody/tr[3]/td[3]/table/tbody/tr[1]/td[2]/table[2]/tbody/tr/td[2]/a"));

    Uname.sendKeys("pgopalakrishnagowda");
    Pwd.sendKeys("Hms@12345");
    Login.click();

    Aries_Select = d1.findElement(By.xpath("html/body/form/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td[3]/table/tbody/tr/td/a"));
    Aries_Select.click();

    Aries_Select1 = d1.findElement(By.xpath("html/body/form/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td[4]/table/tbody/tr/td/a"));
    Aries_Select1.click();
    Thread.sleep(30000L);
    //d1.findElement(By.linkText("CPT Approval")).click();
    //d1.findElement(By.id("cancelButton")).click();

    //Locatable hoverItem = (Locatable) d1.findElement(By.xpath(".//*[@id='mainMenu']/li[2]/span"));
    //Mouse mouse = ((HasInputDevices) d1).getMouse();
    //mouse.mouseMove(hoverItem.getCoordinates());

    //WebElement mianmenu = d1.findElement(By.xpath(".//*[@id='mainMenu']/li[2]/span"));
    //builder.moveToElement(mianmenu).build().perform();
    //builder.moveByOffset(1, 1).build().perform();

    WebDriverBackedSelenium selenium=new
    WebDriverBackedSelenium(d1,d1.getCurrentUrl());
    //selenium.fireEvent(".//*[@id='mainMenu']/li[2]/span","Click");
    selenium.fireEvent("linkText=Configuration","click");
    }
    }



    ReplyDelete
    Replies
    1. The above piece of code is not working so please suggest me how to handle this scenario.

      Delete
    2. Hello Pavan,

      Without application, it is difficult to guess what is incorrect.

      Delete
  27. Ok i will provide the application access.

    Can you please let me know do you have any sample code for verifying webtable celldata?

    i have to create a record after tht it sits in webtable, so i have to verify that data is placed in webtable or not?

    ReplyDelete
  28. Hi Bharath ,

    I really liked ur blog and helping each and everyone ! I am new to Selenium webdriver(using JAVA) and following are the two issues I am facing:

    1 ) How to handle multiple windows i.e Clicking on Login page is going to other page where I need to enter the login . (driver.switchTo() is wt i used and it dint help me out)

    2) How to handle prompts??

    ReplyDelete
    Replies
    1. Hello Arjun,
      To which class your popup belong to
      1. HTML pop-up
      2. JavaScrip pop-up
      3. Win32 pop-up
      4. Modal pop-up

      Delete
  29. Hi Bharath,

    Please help me on, how to handle dynamically changes Xpaths in webdriver

    ReplyDelete
  30. Replies
    1. http://bharath-marrivada.blogspot.in/2012/03/seleniumwebdriver-xpathidentification.html

      Delete
  31. Its a Browser pop up

    package Assessment;
    import java.util.Set;

    import org.junit.Test;
    import org.openqa.selenium.By;
    import org.openqa.selenium.ie.InternetExplorerDriver;


    public class jump {



    @Test
    public void main()

    {
    InternetExplorerDriver driver = new InternetExplorerDriver();

    driver.get("http://preview.extendedcare.com");
    driver.findElement(By.id("anhLogOnButton")).click();

    // Which opens a new login window.

    Using, selenium Webdriver, I want to send Uname and password to this window. How do i do it?
    and the following is wt I used (Using Java)
    try {
    wait(9000);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    driver.getWindowHandles();
    Set availableWindows = driver.getWindowHandles();
    Print("Handle Size:" +availableWindows.size());

    int Windows = 2;
    if (availableWindows.size()== Windows) {


    for (String windowId : availableWindows) {
    driver.switchTo().window(windowId).getTitle();{
    Print("Allscripts logon home page:"+driver.getTitle());



    driver.findElement(By.id("UserNameTextBox")).sendKeys("Test");
    driver.findElement(By.id("PasswordTextBox")).sendKeys("Test=07");


    driver.findElement(By.id("ImageButton1")).click();

    I will be thankful if you can help me on this

    ReplyDelete
    Replies
    1. Hello Arjun,
      To which class your popup belong to
      1. HTML pop-up
      2. JavaScrip pop-up
      3. Win32 pop-up
      4. Modal pop-up

      So that I can suggest a solution

      Delete
    2. Wait till the pop up is loaded and what is the output of
      availableWindows = driver.getWindowHandles();

      Count?

      Delete
    3. 2 . As one Clicking on Login Link (1st window) will bring up one more window(2nd one) where I can enter the UN and PWD . The 1st windoe will be behind the 2 nd one.

      Delete
    4. I got it want you are saying.
      what is count of windows given by availableWindows = driver.getWindowHandles();

      Delete
    5. What is happening when you driver.switchTo().window(WindowIDModal);

      Delete
  32. Login page opens but I am not able to input the keys !

    ReplyDelete
    Replies
    1. I want to know whether webdriver is able to get focus on the new window.
      What is the output of driver.getTitle();
      Is this matching with the login page?

      Delete
  33. No ! the focus is not on the new window

    ReplyDelete
    Replies
    1. At few places, webdriver fails to identify the modal dialog, need to use robot class.

      Delete
  34. how do i do that ? can you pls guide me?

    ReplyDelete
  35. hi i am trying to click on button which opens HTML model window inside iframe , i am not able to perform any operation in that window so can you help in this... i tried to handle window using switch to method and switch to frame but error is like not able to find the locator with frame name

    ReplyDelete
    Replies
    1. Try using driver.switchTo().activeElement(), once done use driver.switchTo().defaultContent().
      If above code is not working use Java script executor.

      Delete
  36. means using java script executor i have to switch to model window ??

    ReplyDelete
    Replies
    1. No. You can click button or enter test. See my other posts to understand.

      Delete
    2. awww thanks it's working ... Thanks alot :):)

      Delete
  37. Hi Bharath,
    Very interesting blog, i had a doubt, i'm trying to get the control on Active window, actually there is a modal dialogue, which starts after giving Login and Password screen , where after modal dialogue, i'm losting the control on next page and when i tried to click the elements in the next page, i',m turning up with an error... saying unable to find the element. Please advice me on this..

    ReplyDelete