In this cutting-edge technology era where innovation is progressing at a huge speed, the complexity in the design of the applications is likewise being more complexed day by day, and automating them additionally turns out to be a very challengeable task.
Such a complex scenario is automating popups or pages opened in new tabs. You may have to switch in between multiple tabs open in a browser to perform some actions on them. If you are a beginner in Selenium you will get stuck and feel a bit annoying. Having said that, the good thing is that its a quite an easier thing.
This article will describe to you how to handle a new tab in Selenium Webdriver and perform all sorts of activities that will sort out all of your problems related to a new tab.
Handle a New Tab in Selenium WebDriver
You will learn the following things.
- Open a link in a New Tab in Selenium WebDriver and perform some action on it.
- Open a link in a New Tab in Selenium WebDriver Using JavaScript and perform some action on it.
- Open New Tab in Selenium WebDriver Action Class and perform some action on it.
- Switching back and forth between parent and new tab
We will use windows handle to handle new tabs. If you want to know more about window handles please refer to my post How to Handle Multiple Windows In Selenium WebDriver.
How to Open a Link in a New Tab in Selenium WebDriver and Perform some action on it
You can simply open a link in a new tab by following the syntax
1 2 3 4 |
//Opening a link in a new tab Using Selenium WebDriver WebElement linkName= driver.findElement(By required locator")); String keyString = Keys.CONTROL+Keys.SHIFT.toString()+Keys.ENTER.toString(); linkName.sendKeys(keyString); |
The following code shows how to print the title and the page heading after opening a link on a new tab.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
import java.util.ArrayList; import java.util.Iterator; import java.util.Set; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class OpeningNewTabExample1 { public static void main(String[] args) throws InterruptedException { //Setting the path of Chrome Browser Driver String BrowserDriverPath= "C:\\SeleniumBrowserDrivers\\chromedriver.exe"; //Setting System property for Chrome browser Driver. System.setProperty("webdriver.chrome.driver",BrowserDriverPath); //Create a new Instance for Chrome Browser WebDriver driver = new ChromeDriver(); //Defining Implicit Wait for 20 Seconds driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.get("https://www.w3schools.com/"); driver.manage().window().maximize(); //Strong Parent window handle to switch back to parent widow whenever required String parent=driver.getWindowHandle(); //Opening a link in a new tab in Selenium without action class Method 1 WebElement linkCSS= driver.findElement(By.xpath("//a[text()='Learn CSS']")); String keyString = Keys.CONTROL+Keys.SHIFT.toString()+Keys.ENTER.toString(); linkCSS.sendKeys(keyString); //getting all window handles Set<String> Winhandles=driver.getWindowHandles(); for(String hndl: Winhandles) { //if the child widow handle is not same as parent window handle if(!hndl.equalsIgnoreCase(parent)) { //switching to the opened tab driver.switchTo().window(hndl); //opening the URL saved. System.out.println("New Tab Window Title:" + driver.getTitle()); System.out.println("New Tab Window Page Heading: "+ driver.findElement(By.xpath("//*[@id=\"main\"]/h1")).getText()); } } } } |
Output
New Tab Window Title: CSS Tutorial
New Tab Window Page Heading: CSS Tutorial
How to Open a Link in a New Tab in Selenium WebDriver Using JavaScript and Perform some action on it
You can use the following syntax to open a link in a new tab using JavaScript.
((JavascriptExecutor)driver).executeScript(“window.open(‘ ” + linkVaue +” ‘);”);
The following code shows how to use the above syntax.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
package tabautomation; import java.util.ArrayList; import java.util.Iterator; import java.util.Set; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class OpeningNewTabExample2 { public static void main(String[] args) throws InterruptedException { //Setting the path of Chrome Browser Driver String BrowserDriverPath= "C:\\SeleniumBrowserDrivers\\chromedriver.exe"; //Setting System property for Chrome browser Driver. System.setProperty("webdriver.chrome.driver",BrowserDriverPath); //Create a new Instance for Chrome Browser WebDriver driver = new ChromeDriver(); //Defining Implicit Wait for 20 Seconds driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.get("https://www.w3schools.com/"); driver.manage().window().maximize(); //Strong Parent window handle to switch back to parent widow whenever required String parent=driver.getWindowHandle(); //Opening a link in a new tab in Selenium without action class Method 1 String linkVaueCSS= driver.findElement(By.xpath("//a[text()='Learn CSS']")).getAttribute("href"); ((JavascriptExecutor)driver).executeScript("window.open('" + linkVaueCSS +"');"); //getting all window handles Set<String> Winhandles=driver.getWindowHandles(); for(String hndl: Winhandles) { //if the child widow handle is not same as parent window handle if(!hndl.equalsIgnoreCase(parent)) { //switching to the opened tab driver.switchTo().window(hndl); //opening the URL saved. System.out.println("New Tab Window Title:" + driver.getTitle()); System.out.println("New Tab Window Page Heading: "+ driver.findElement(By.xpath("//*[@id=\"main\"]/h1")).getText()); } } } } |
How to Open a Link in a New Tab in Selenium WebDriver Using Action Class and Perform some action on it
You can use the following syntax to open a link in a new tab using the Action class.
1 2 3 4 5 6 |
Actions actions = new Actions(driver); actions.keyDown(Keys.LEFT_CONTROL) .click(linkElement) .keyUp(Keys.LEFT_CONTROL) .build() .perform(); |
The following code shows how to use the above syntax.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
import java.util.Set; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class OpeningNewTabExample3 { public static void main(String[] args) throws InterruptedException { //Setting the path of Chrome Browser Driver String BrowserDriverPath= "C:\\SeleniumBrowserDrivers\\chromedriver.exe"; //Setting System property for Chrome browser Driver. System.setProperty("webdriver.chrome.driver",BrowserDriverPath); //Create a new Instance for Chrome Browser WebDriver driver = new ChromeDriver(); //Defining Implicit Wait for 20 Seconds driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.get("https://www.w3schools.com/"); driver.manage().window().maximize(); //Strong Parent window handle to switch back to parent widow whenever required String parent=driver.getWindowHandle(); //Opening a link in a new tab in Selenium using action class WebElement linkElement = driver.findElement(By.xpath("//*[@id=\"mySidenav\"]/div/a[5]")); Actions actions = new Actions(driver); actions.keyDown(Keys.LEFT_CONTROL) .click(linkElement) .keyUp(Keys.LEFT_CONTROL) .build() .perform(); //getting all window handles Set<String> Winhandles=driver.getWindowHandles(); for(String hndl: Winhandles) { //if the child widow handle is not same as parent window handle if(!hndl.equalsIgnoreCase(parent)) { //switching to the opened tab driver.switchTo().window(hndl); //opening the URL saved. System.out.println("New Tab Window Title:" + driver.getTitle()); System.out.println("New Tab Window Page Heading: "+ driver.findElement(By.xpath("//*[@id=\"main\"]/h1")).getText()); } } } } |
Switching Between Parent and New Tab
The following example will open a new tab and switch to the new tab. It will retrieve the title and heading of the new tab window and print them. After that, it will switch back to the parent window and print its title.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
import java.util.ArrayList; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class OpeningNewTabExample4 { public static void main(String[] args) throws InterruptedException { //Setting the path of Chrome Browser Driver String BrowserDriverPath= "C:\\SeleniumBrowserDrivers\\chromedriver.exe"; //Setting System property for Chrome browser Driver. System.setProperty("webdriver.chrome.driver",BrowserDriverPath); //Create a new Instance for Chrome Browser WebDriver driver = new ChromeDriver(); //Defining Implicit Wait for 20 Seconds driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.get("https://www.w3schools.com/"); driver.manage().window().maximize(); //Strong Parent window handle to switch back to parent widow whenever required String parent=driver.getWindowHandle(); //Opening a link in a new tab in Selenium using action class WebElement linkElement = driver.findElement(By.xpath("//*[@id=\"mySidenav\"]/div/a[5]")); Actions actions = new Actions(driver); actions.keyDown(Keys.LEFT_CONTROL) .click(linkElement) .keyUp(Keys.LEFT_CONTROL) .build() .perform(); ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles()); driver.switchTo().window(tab.get(1)); //opening the URL saved. System.out.println("New Tab Window Title:" + driver.getTitle()); System.out.println("New Tab Window Page Heading: "+ driver.findElement(By.xpath("//*[@id=\"main\"]/h1")).getText()); //switch to the parent window driver.switchTo().window(parent); System.out.println("Parent Window Title:" + driver.getTitle()); } } |
Note: If you have to deal with more than two tabs and switch in between any of the tabs it’s better to get the window handles in a set and iterate them to retrieve their window title.If the expected title is matched then switch to that window. Please refer to the post How to Handle Multiple Windows In Selenium WebDriver to see the example.
Open Multiple Tabs and Navigate to Different URLs On each of Them and Iterate Them
So far we have seen how to open a link in a new tab and performed some action on it. You may have a requirement that after opening a page you may have to open one or more than one new tab and then open different URLs on them and do some automation testing on them. I am going to show you how to do it right away.
We can open new empty tabs in the following two ways:
- Using Robot Class
- Using JavaScript
Syntax of the opening new tab using Robot class
1 2 3 4 5 6 |
//Opening a new tab Using Robot Class Robot r = new Robot(); r.keyPress(KeyEvent.VK_CONTROL); r.keyPress(KeyEvent.VK_T); r.keyRelease(KeyEvent.VK_CONTROL); r.keyRelease(KeyEvent.VK_T); |
The above code opens a tab using the simulating keypress event “CTRL+ t” command of the keyboard. The same thing can be done using sendKeys but it may or may not work depending on the browser you are using. You can use the following sendKeys command to open a new tab.
driver.findElement(By.cssSelector(“body”)).sendKeys(Keys.CONTROL+ “t”);
Syntax of the opening new tab using JavaScript
The following is the syntax to open a new tab using JavaScript
((JavascriptExecutor)driver).executeScript(“window.open()”);
We will use both the above commands to open new tabs in the following test scenario.
Test Scenario
- Open a browser and navigate to W3school
- Open a new tab using Robot class
- Open a new tab using javascript
- Open Google at tab index 1
- Open Facebook at tab index 2
- Iterate the tabs and print their title
Example of Opening Multiple Tabs and Navigating to Different URLs on each of them
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class OpeningNewTabExample5 { public static void main(String[] args) throws InterruptedException, AWTException { //Setting the path of Chrome Browser Driver String BrowserDriverPath= "C:\\SeleniumBrowserDrivers\\chromedriver.exe"; //Setting System property for Chrome browser Driver. System.setProperty("webdriver.chrome.driver",BrowserDriverPath); //Create a new Instance for Chrome Browser WebDriver driver = new ChromeDriver(); //Defining Implicit Wait for 20 Seconds driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.get("https://www.w3schools.com/"); driver.manage().window().maximize(); //Strong Parent window handle to switch back to parent widow whenever required String parent=driver.getWindowHandle(); //Opening a new tab Using Robot Class Robot r = new Robot(); r.keyPress(KeyEvent.VK_CONTROL); r.keyPress(KeyEvent.VK_T); r.keyRelease(KeyEvent.VK_CONTROL); r.keyRelease(KeyEvent.VK_T); //Opening a tab Using JavaScriptss ((JavascriptExecutor)driver).executeScript("window.open()"); ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles()); driver.switchTo().window(tabs.get(1)); driver.get("https://google.com"); driver.switchTo().window(tabs.get(2)); driver.get("https://facebook.com"); //Iterating through all opened tab Using Selenium for(int i=0; i<tabs.size();i++) { System.out.println("Title of Tab of at Index ("+i+") is :" + driver.switchTo().window(tabs.get(i)).getTitle()); } } } |
OutPut
Title of Tab of at Index (0) is: W3Schools Online Web Tutorials
Title of Tab of at Index (1) is: Google
Title of Tab of at Index (2) is: Facebook – log in or sign up
Conclusion
We have seen that there are different ways to open a new tab. You can use any of them that suits you better. If you have any comment or query please mention in the comment box.
Recommended Posts
- Handle Dynamic Web Tables In Selenium WebDriver
- Select Value From Multi-Select Dropdown In Selenium WebDriver And Dropdown with CheckBoxes
- Top #23 Most Useful Selenium WebDriver Commands That You Must know
- XPath in Selenium WebDriver with Example
- Wait Commands in Selenium WebDriver | Implicit | Explicit | Fluent Wait
- How to Use CSS Selector in Selenium WebDriver | 13 Examples
- Intuitive Way of MySQL Database Testing in Selenium | LeanFT
- Read and Write Excel File in Java Using Apache POI Lib