-1

I'm creating test scripts in Selenium WebSriver using Eclipse, and have hit a snag in a scenario whereby I have a parent window, I click on a link on that window and a child window opens. I then want to close the child window and carry out functions again on the parent window.

My code is as below:

public static void daysInStockSelectContract(InternetExplorerDriver driver) {
    driver.findElement(By.xpath(".//*[@id='page-content']/table/tbody/tr[1]/td[1]/a")).click();

    for(String winHandle : driver.getWindowHandles()) {
        driver.switchTo().window(winHandle);
        driver.close();
    }
 }

When I run the above code, the child window remains open whilst the parent window closes, which is the opposite effect of what I wanted. Also an error as follows is shown in the console:

"Exception in thread "main" org.openqa.selenium.remote.SessionNotFoundException: session 1ff55fb6-71c9-4466-9993-32d7d9cae760 does not exist"

I'm using IE WebDriver for my Selenium scripts.


UPDATE - 17/11/14

Subh, here is the code I used from the link you kindly send over which unfortunately doesn't appear to work.

public static void daysInStockSelectContract(InternetExplorerDriver driver) {
    //get the parent handle before clicking on the link
    String winHandleBefore = driver.getWindowHandle();

    driver.findElement(By.xpath(".//*[@id='page-content']/table/tbody/tr[1]/td[1]/a")).click();

    // the set will contain only the child window now. Switch to child window and close it.
    for(String winHandle : driver.getWindowHandles()) {
        driver.switchTo().window(winHandle);
    }
    driver.close();
    driver.switchTo().window(winHandleBefore);
}
t0mppa
  • 3,983
  • 5
  • 37
  • 48
Andy Tilston
  • 227
  • 1
  • 5
  • 18

3 Answers3

1

Probably, the switching to child window didn't happen properly.

Hence, 'driver.close()' is closing the parent window, instead of child window. Also, since the parent window has been closed, it implies the session has been lost which gives the error 'SessionNotFoundException'.

This link will help you out in properly switching between windows

On another note, just an advice. Rather than passing "driver" as a parameter, why don't you make it a static variable. It will be easily accessible to all the methods inside the class and it's subclasses too, and you don't have to bother about passing it each time to a method.. :)


Below is the code that you've requested in your comment (Unrelated to the question above)

public class Testing_anew {

    public static WebDriver driver;

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

        driver = new FirefoxDriver();

        driver.manage().window().maximize();

        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

      }

    public static void testmethod(){

    driver.findElement(By.xpath("//some xpath")).click();
   }

Updated Code 19/11/14

public static void daysInStockSelectContract(InternetExplorerDriver driver) {
    //get the parent handle before clicking on the link 
    String winHandleBefore = driver.getWindowHandle();

    System.out.println("Current handle is: "+winHandleBefore);

    driver.findElement(By.xpath(".//*[@id='page-content']/table/tbody/tr[1]/td[1]/a")).click();

    // Iterating through the set of window handles till the child window's handle, that is infact
    // not equal to the current window handle, is found
    for(String winHandle : driver.getWindowHandles()) {
       if(!winHandle.equals(winHandleBefore)){
                System.out.println("Child handle is: "+ winHandle);
                //Sleeping for 4 seconds for detecting Child window
                try{
                    Thread.sleep(4000);
                   }catch(InterruptedException e){
                    System.out.println("Caught exception related to sleep:"+e.getMessage());
                   }
                driver.switchTo().window(winHandle);
                break;
            }
    } 

    System.out.println("AFTER SWITCHING, Handle is: "+driver.getWindowHandle());

    driver.close();

    //Sleeping for 4 seconds for detecting Parent window
    try{
        Thread.sleep(4000);
       }catch(InterruptedException e){
        System.out.println("Caught exception related to sleep:"+e.getMessage());
       }

    driver.switchTo().window(winHandleBefore); // Switching back to parent window

     System.out.println("NOW THE CURRENT Handle is: "+driver.getWindowHandle());

     //Now perform some user action here with respect to parent window to assert that the window has switched properly


} 
Community
  • 1
  • 1
Subh
  • 4,354
  • 1
  • 13
  • 32
  • Hi Subh, thanks for the update. The error output in the console now shows the two different handles and is as below "Current handle is: f5ec1357-830a-4ea6-9632-d1da8ac90bda Child handle is: ffe5b144-a6bd-49b4-b034-b0c6e2190280 Exception in thread "main" org.openqa.selenium.NoSuchWindowException: No window found (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 1.59 seconds" Hope this helps :-) – Andy Tilston Nov 18 '14 at 12:07
  • The problem is while switching to Window, i.e., in this code `driver.switchTo().window(winHandle);`. Try running the same code using **FirefoxDriver**. If it runs please let me know. – Subh Nov 18 '14 at 12:17
  • Hi Subh, I've run the code in Firefox and it does indeed work. However, I'm running this on IE as the website I am testing is an intranet site where all the users are on IE. – Andy Tilston Nov 18 '14 at 12:39
  • Also, it may be irrelevant, but in Firefox when the action is completed the console displays the following "Current handle is: {dee6212a-ff49-42f0-b413-00dfa4178b23} Child handle is: {15715675-3a64-45f5-9342-641c025ee171} AFTER SWITCHING, Handle is: {15715675-3a64-45f5-9342-641c025ee171} Exception in thread "main" org.openqa.selenium.NoSuchWindowException: Window not found. The browser window may have been closed." So even though the action has been completed, the 'AFTER SWITCHING' text implies that we are on the same handle as the child :-/ – Andy Tilston Nov 18 '14 at 12:43
  • Which version of IE are you using ? – Subh Nov 18 '14 at 12:43
  • I've got a windows 8 machine, so it forces me to use IE11 – Andy Tilston Nov 18 '14 at 12:44
  • I've re-run the test in IE, given that we now know it's an IE issue. I tried running the test with compatability mode enabled against the website. This time the output is slightly different "Current handle is: 05357e32-80f8-47b1-aef5-b41a993e0af9 AFTER SWITCHING, Handle is: 05357e32-80f8-47b1-aef5-b41a993e0af9 Exception in thread "main" org.openqa.selenium.remote.SessionNotFoundException: session a99d692c-3832-4e01-8f7b-bd00aee9b963 does not exist" – Andy Tilston Nov 18 '14 at 12:59
  • For IE-11, you need to do a few settings in the browser before proceeding. The 3rd point, 4th, and 5th point of the link under **Required Configuration**: [https://code.google.com/p/selenium/wiki/InternetExplorerDriver#Required_Configuration](https://code.google.com/p/selenium/wiki/InternetExplorerDriver#Required_Configuration) will do. Let me know, if you need help setting the above – Subh Nov 18 '14 at 13:03
  • Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackoverflow.com/rooms/65145/discussion-on-answer-by-subh-switch-from-child-to-parent-window-in-selenium-webd). – Taryn Nov 18 '14 at 13:05
  • @bluefeet : I apologise for that. But since Andy has yet to have the bare minimum reputation points to chat, I wasn't able to switch to chat mode. Can you suggest any other way please, because I am afraid I won't be able to communicate with him via chat? – Subh Nov 18 '14 at 13:08
  • @Subh That should be resolved since I moved the comments to chat. It overrides the rep requirement so Andy should be able to join. – Taryn Nov 18 '14 at 13:09
0

When you loop through the windowHandles, the first handle is the parent handle. So when you say driver.close(), the parent window is getting closed. This can be avoided by using the following code:

public static void daysInStockSelectContract(InternetExplorerDriver driver) {
    //get the parent handle before clicking on the link
    String parentHandle = driver.getWindowHandle();

    driver.findElement(By.xpath(".//*[@id='page-content']/table/tbody/tr[1]/td[1]/a")).click();

    //get all the window handles and assign it to a set 
    //It will include child window and parentwindow
    Set<String> windowHandles = driver.getWindowHandles();

    System.out.println("No of Window Handles: " + windowHandles.size());

    //remove the parent handle from the set
    windowHandles.remove(parentHandle);

    // the set will contain only the child window now. Switch to child window and close it.
    for(String winHandle : driver.getWindowHandles()) {

strong text driver.switchTo().window(winHandle); driver.close(); } }

If you get the size as 1 (no of windowHandles as one) or is getting same error message, then probably the window is an alert box. To handle the alert box you can use the following code just after clicking on the link.

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

Try this code for debugging

public static void daysInStockSelectContract(InternetExplorerDriver driver) {
    // get the parent handle before clicking on the link
    String parentHandle = driver.getWindowHandle();
    System.out.println("ParentHandle : " + parentHandle);
    driver.findElement(
            By.xpath(".//*[@id='page-content']/table/tbody/tr[1]/td[1]/a"))
            .click();

    // get all the window handles and assign it to a set
    // It will include child window and parentwindow
    Set<String> windowHandles = driver.getWindowHandles();

    System.out.println("No of Window Handles: " + windowHandles.size());

    // remove the parent handle from the set
    windowHandles.remove(parentHandle);

    // the set will contain only the child window now. Switch to child
    // window and close it.
    for (String winHandle : driver.getWindowHandles()) {
        driver.switchTo().window(winHandle);
        System.out.println("Child Handle : " + winHandle);
        driver.close();
    }

    // get the window handles again, print the size
    windowHandles = driver.getWindowHandles();
    System.out.println("No of Window Handles: " + windowHandles.size());
    for (String winHandldes : windowHandles) {
        System.out.println("Active Window : " + winHandldes);
    }

    driver.switchTo().window(parentHandle);
}
StrikerVillain
  • 3,719
  • 2
  • 24
  • 41
  • Hey there, many thanks for your help on this :-) Unfortunately, I am still having an issue in that the child window fires up, but the parent window still closes. The error I get is: "Exception in thread "main" org.openqa.selenium.remote.SessionNotFoundException: session 84742c89-b161-4112-9de7-2fde02cdacb8 does not exist Command duration or timeout: 0 milliseconds" Do you have any ideas about what may be causing this? Many thanks again. – Andy Tilston Nov 17 '14 at 09:32
  • did this code work? If yes, please accept the answer :) – StrikerVillain Nov 17 '14 at 09:34
  • Hi there, I'm still getting the issue actually. Hope you can help with the problem I am still getting :-) – Andy Tilston Nov 17 '14 at 09:38
  • Can you try out the edited code above. I have added an extra line to print the number of window handles. If you are still getting the error or if size is zero then your other window would be acting as a alert window. I have also added the code to handle alert. – StrikerVillain Nov 17 '14 at 12:36
  • Hi, thanks for the response. I added the code to handle the alert box but I don't think that is the issue as I get an error saying: "Exception in thread "main" org.openqa.selenium.NoAlertPresentException: No alert is active" The next thing I tried was to add in the line of code to print the number of window handles. The value I get back is '2'. Any ideas what this might be? – Andy Tilston Nov 17 '14 at 14:17
  • Just for debugging purpose please try the updated code. We will try to print the window handles value and try to figure this out. – StrikerVillain Nov 17 '14 at 20:06
  • Hi there, Subh has kindly been helping me with this. There are a raft of notes above which hopefully shed some light on the issue. It appears the problem is limited to IE as when I run the test in Firefox I don't get the issue. Unfortunately, I am required to use IE for my automation, here. – Andy Tilston Nov 18 '14 at 12:57
0

I managed to resolve this issue by using the steps outlined by Subh above. Especially, ensure that 'Enable Protected Mode' is disabled on the 'Security' tab of 'Internet Options'

Andy Tilston
  • 227
  • 1
  • 5
  • 18