0

I am working on 2 URLS . I need to open the first URL ,perform some action and open the second URL.

openURL1() { perform action }

openURL2() { perform action } switch back to URL1

when I use driver.get or driver.navigate , URL1 gets closed. Is there anyway to retain the window with URL1 while opening URL2? I am working with selenium and JAVA

user1851202
  • 11
  • 1
  • 6
  • Possible duplicate of [How to open a new tab using Selenium WebDriver with Java?](https://stackoverflow.com/questions/17547473/how-to-open-a-new-tab-using-selenium-webdriver-with-java) – santhosh kumar Jun 15 '17 at 09:40
  • i was asking how do i retain old window and still manage to open a new tab. In my case the previous window gets closed when i open a new one (tab or window) – user1851202 Jun 15 '17 at 09:43

3 Answers3

3

If the second tab is not opened through an action that is performed in first tab, then you can use two driver objects, so that you'll have control of both the browsers with different driver objects.

    WebDriver driver = new ChromeDriver();
    driver.get("https://news.ycombinator.com");

    WebDriver driver1 = new ChromeDriver();
    driver1.get("https://www.google.com");

By this approach you can use driver to control URL1 and driver1 to control URL2.

1

You may use javascript to open new tab

(JavascriptExecutor(driver)).executeScript("window.open();");
1

Here is the Answer to your Question:

Here is the working code block which opens the URL http://www.google.com, prints Working on Google on the console, opens http://facebook.com/ in a new tab, prints Working on Facebook in the console, closes the tab which opened the URL http://facebook.com/, gets you back to the tab which opened the URL http://www.google.com and finally closes it.

    System.setProperty("webdriver.gecko.driver", "C:\\your_directory\\geckodriver.exe");
    WebDriver driver =  new FirefoxDriver();
    driver.get("http://www.google.com");
    String first_tab = driver.getWindowHandle();
    System.out.println("Working on Google");
    ((JavascriptExecutor) driver).executeScript("window.open('http://facebook.com/');");
    Set<String> s1 = driver.getWindowHandles();
    Iterator<String> i1 = s1.iterator();
    while(i1.hasNext())
    {

        String next_tab = i1.next();
        if (!first_tab.equalsIgnoreCase(next_tab))
        {
            driver.switchTo().window(next_tab);
            System.out.println("Working on Facebook");
            driver.close();
        }
    }
    driver.switchTo().window(first_tab);
    driver.close();

Let me know if this Answers your Question.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352