In this Example, we will open a link in New tab, So below mentioned step you have to perform to achieve this :
1. Create an XPath or find a unique path of the link.
Ex : As Mentioned in ScreenShot we are going to open a 'CORE JAVA' Link in new Tab So we have taken a Unique Path.
2. Get 'href ' Attribute from WebElement, because of Every Link Consist of a Unique URL
1. Create an XPath or find a unique path of the link.
Ex : As Mentioned in ScreenShot we are going to open a 'CORE JAVA' Link in new Tab So we have taken a Unique Path.
![]() |
Image 1 |
2. Get 'href ' Attribute from WebElement, because of Every Link Consist of a Unique URL
String UrlofLink = driver.findElement(By.xpath("//a[contains(text(),'Core Java')]")).getAttribute("href");
or you can Devide Script into Two Parts
WebElement Link = driver.findElement(By.xpath("//a[contains(text(),'Core Java')]")); String UrlofLink=Link.getAttribute("href");
3. To Open a New Tab you have to use JavaScript Executor and WindowHandler, JavaScriptExecutor has Used for Open a Blank new Tab and Through windowHandler, you will get a count of current Tab based on Count you can switch to parent tab to child Tab and Vice-versa.public class OpenNewTab{
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.chrome.driver",".\\Exe\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
String baseUrl = "http://www.QaMantra.com/";
driver.get(baseUrl);
// Get a Url from Link
WebElement Link = driver.findElement(By.xpath("//a[contains(text(),'Core Java')]"));
String UrlofLink=Link.getAttribute("href");
// To open a New tab
((JavascriptExecutor)driver).executeScript("window.open()");
//Get a Count of Current open Window
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
//switches to new tab
driver.switchTo().window(tabs.get(1));
// To open a link in New Tab
driver.navigate().to(UrlofLink);
// switch back to main screen
driver.switchTo().window(tabs.get(0));
}}