Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium WebDriver: Open new tab instead of a new window

I am using Selenium WebDriver. Every link is opened in a new browser window. It is not convenient for me. How can I change it so that it opens just in new tab?

like image 683
khris Avatar asked Jul 06 '12 08:07

khris


1 Answers

Selenium has the ability to switch over tabs now-a-days. The below code1: will work for firefox, code2: for IE and chrome by using Robot class we can do and the control doesnt move automatically to current tab so we need to switch to the current tab by using window handles method. The given below code will work well When we are running individual script but when running as a suite you may feel the pain in performing key board events. In order to avoid that we got to go with other possibility by using user defined javascript method by using javascript executor in selenium-Java.

We can switch between windows and tabs by identifying its name allocated for each and every windows which we open and the name will be in alphanumeric character.

    ***Code 1***
    //First tab(default tab)
    driver.navigate().to("http://www.google.com");
    driver.manage().window().maximize();

    //second tab
    driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
    driver.navigate().to("https://yahoo.com");

    //third tab
    driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
    driver.navigate().to("http://www.google.com");

    //move to very first tab.
    driver.findElement(By.cssSelector("body"))
            .sendKeys(Keys.CONTROL + "\t");

    // To close the current tab.    
    driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "w");
    **code 2**
    driver.navigate().to("http://www.google.com");
    driver.manage().window().maximize();


    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_T);

    Set<String> handles = driver.getWindowHandles();
    List<String> handlesList = new ArrayList<String>(handles);
    String newTab = handlesList.get(handlesList.size() - 1);

    // switch to new tab
    driver.switchTo().window(newTab); 
    driver.get("http://www.yahoo.com");
like image 158
Das Prakash Avatar answered Sep 28 '22 10:09

Das Prakash