AutomationTester
AutomationTester

Reputation: 81

Switching to elements of new tab - selenium

On clicking an option from a dropdown using selenium webdriver, the link opens in a new tab.

So, when trying to locate elements, I am getting a null pointer exception. How to switch to the new tab to locate elements on it?

I am working on chrome browser using java language.

Upvotes: 0

Views: 1682

Answers (3)

sunil dewna
sunil dewna

Reputation: 11

Here you can open new tab and switch then open a new url in new tab


    package com.crm.qa.BaseTest;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class NewTabChrome {

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

        System.setProperty("webdriver.chrome.driver", 
                "C:/Users/sunil/Downloads/chromedriver_win32 (2)/chromedriver.exe");

        WebDriver driver = new ChromeDriver();//open browser
        driver.manage().window().maximize();//browser maximize
        driver.get("http://www.google.com");//open google 

        //open new tab 
        for(int i = 0; i<=1;i++){
        Robot rob = new Robot();
        rob.keyPress(KeyEvent.VK_CONTROL);
        rob.keyPress(KeyEvent.VK_T);
        rob.keyRelease(KeyEvent.VK_CONTROL);
        rob.keyRelease(KeyEvent.VK_T);
        ArrayList<String> tabs1 = new ArrayList<String> (driver.getWindowHandles());
        //Switch to new tab
        driver.switchTo().window((String) tabs1.get(i));
    }
        //open facebook
        driver.get("http://facebook.com");
        driver.quit();
    }
}

Upvotes: 0

AutomationTester
AutomationTester

Reputation: 81

I have found another solution, which is working for me, - using windows handlers

String parentWindowHandler=driver.getWindowHandle();// Store your parent window
String subWindowHandler = null;
Set<String> handles = driver.getWindowHandles(); // get all window handles
            Iterator<String> iterator = handles.iterator();
            while (iterator.hasNext()){
                subWindowHandler = iterator.next();
            }
driver.switchTo().window(subWindowHandler); // switch to popup window

and you can switch back to parent window when required by driver.switchTo().window(parentWindowHandler);

Upvotes: 1

Yuga
Yuga

Reputation: 49

You can use robot class to switch to the new tab using keyboard shortcuts CTRL+SHIFT+TAB - switch between tabs

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_SHIFT);
robot.keyRelease(KeyEvent.VK_CONTROL);

You can also use one of the following methods: Switch tabs using Selenium WebDriver with Java

Upvotes: 0

Related Questions