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?
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With