0

I am using below code to test window handle.

New page opens in new tab but switchTo command do not switch to it.

public static void main(String[] args) {
        Actions act = new Actions(driver);
        driver.get("https://www.google.co.in");

        String parentWin = driver.getWindowHandle();
        act.keyDown(Keys.LEFT_CONTROL).perform();
        driver.findElement(By.linkText("Images")).click();

        for(String newWindow: driver.getWindowHandles()){
            driver.switchTo().window(newWindow);
            driver.findElement(By.id("lst-ib")).sendKeys("hello world");
            driver.findElement(By.name("btnG")).click();
            driver.close();
        }


        driver.switchTo().window(parentWin);
        driver.findElement(By.linkText("Gmail")).click();


    }

This code voted as correct answer here: How to handle the new window in Selenium WebDriver using Java? from @CODEBLACK

Community
  • 1
  • 1
paul
  • 4,333
  • 16
  • 71
  • 144
  • read the question title. then read detail description/scenario, if you think something missing put it in comment box. https://open.bufferapp.com/how-to-read-more-and-remember-it-all/ – paul Sep 06 '15 at 13:02

1 Answers1

1

My understanding of how this works is that each driver instance is a browser, not a tab. But... when I looked up how to do this I see code samples that state that your code should work. So I'm not sure if it used to work and doesn't now or if they were saying tabs but meant new browser windows... either way, I found a solution. There are two ways to do this.

  1. Open the new page in a new browser window instead of a tab. This is an easy fix... you just change your CTRL keypress to a SHIFT.

    act.keyDown(Keys.SHIFT).perform();

  2. The other way I haven't tried but it is described in the link below. It basically involves using the CTRL+TAB keyboard shortcut to move through the open tabs. You are going to have to track where you are and depending on the number of open tabs, this could get pretty hairy pretty fast.

http://design-interviews.blogspot.com/2014/11/switching-between-tabs-in-same-browser-window.html

I would recommed #1 because it feels less hacky but you may have a requirement that it opens in a tab and have to go with #2.

JeffC
  • 22,180
  • 5
  • 32
  • 55
  • I want to downvote, because I already know "other way around" of it. I specifically want to know why `switchTo` not working. – paul Sep 07 '15 at 09:12
  • I explained that in my answer... it's working fine, you just are expecting it to work in a case that it's not intended to be used. If you knew about the alternative, you should have put that in the answer to save us time researching alternatives. – JeffC Sep 07 '15 at 13:51
  • He's right. Currently Selenium doesn't support switching between tabs (Note that doesn't support doesn't mean you can't hack round the issue) – Ardesco Sep 09 '15 at 15:27