Handle Multiple Browser Tabs and Alerts with Selenium WebDriver

In this tutorial, we will learn to handle multiple browser tabs within a single Selenium script. Selenium WebDriver does not provide any commands for this task. 

But we can make use of the existing Selenium commands in a smarter way to automate this scenario. Although this scenario is quite rare and you will not encounter it usually.



1. Handle Multiple Browser Tabs with Selenium

Use Selenium Actions Class to Handle Multiple Browser Tabs

Actions Class in Selenium is a special class which provides us very useful commands, which helps us to replicate Keyboard and Mouse events i.e., press/release any Key, move cursor, drag and drop, right click, double click etc. You can learn about Actions Class in detail here

In our scenario, we'll make use of Key control commands of Actions class to automate open and automate multiple browsers. Let's understand the whole code logic step by step.

1.1. Launch google.com with Selenium WebDriver

This is the most common part, we'll launch google.com with Selenium WebDriver as usual.

// Set Driver path
System.setProperty("webdriver.chrome.driver", "C:\\AUTOMATION\\chromedriver.exe");

// Initialize driver  
WebDriver driver=new ChromeDriver();

//Maximize browser window   
driver.manage().window().maximize();  

//Go to URL  
driver.get("http://www.google.com");  

//Set timeout  
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  

1.2. Automate Opening of two browser tabs

Now our first browser tab is opened and google.com is launched inside it. So, step 2 is to open our second browser tab. Like we already know that manually we can open a new tab in a browser by pressing 'ctrl' key and 't' key together. We are going to automate of this shortcut using Selenium Actions Class.

// Open new tab by pressing ctrl + t
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");  

//Go to URL  
driver.get("http://www.gmail.com");  

//Set new tab timeout  
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  

// Do some operations on gmail like login      

1.3. Automate Switching between two tabs during execution of automation script

We can switch between different tabs on a browser by pressing 'ctrl' and 'tab'. We'll automate same with Actions class.

// Switch back to first tab (google.com) by pressing ctrl + tab
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "\t");  
driver.switchTo().defaultContent();  
Thread.sleep(2000);  

// Do some operation on google.com

Important - We can also use Robot Class of Java to handle multiple tabs.

Code to Handle two Browser Tabs with Selenium:

public class SwitchBetweenBrowserTab {  

 public static void main(String[] a) throws InterruptedException {  
     
      // Set Driver path
      System.setProperty("webdriver.chrome.driver", "C:\\AUTOMATION\\geckodriver.exe");
// Initialize driver WebDriver driver = new FirefoxDriver(); //Maximize browser window driver.manage().window().maximize(); //Go to URL driver.get("http://www.google.com"); //Set timeout driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Open new tab driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t"); //Go to URL driver.get("http://www.gmail.com"); //Set new tab timeout driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Do some operation driver.findElement(By.id("gmail-sign-in")).click(); driver.findElement(By.id("Email")).sendKeys("WebDriver"); driver.findElement(By.id("Passwd")).sendKeys("WebDriver"); driver.findElement(By.id("signIn")).click(); Thread.sleep(2000); // Switch first tab driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "\t"); driver.switchTo().defaultContent(); Thread.sleep(2000); // Write search String driver.findElement(By.id("gbqfq")).sendKeys("WebDriver"); // Click on Search button driver.findElement(By.id("gbqfb")).click(); Thread.sleep(2000); // Browser close driver.close(); } }

Program Explanation:
  • Open Google.com
  • Then open a new tab by making use of Key class. By combination of CTRL + t key a new browser tab will be opened.
  • Open Gmail.com in that tab.
  • Perform some actions on Gmail sign in page.
  • Switch back to google.com tab by pressing Ctrl + \t
  • Now enter some keywords in google search box
  • Close the browsers.


2. Handle Alerts with Selenium WebDriver

In this section of post, we will learn to handle alerts or popups with Selenium WebDriver using Java. Generally there are two types of alerts:
  1. Web Alerts
  2. Window Alerts
Out of these two only web based alerts can be handled using Selenium WebDriver. Window alerts cannot be handled using selenium WebDriver, but there are other ways of handling the window alerts and we will discuss that strategy in next post. In this post we are going to handle web based alerts.

2.1. What is a Web Alert?

A Web alert is generally a JavaScript based pop-up that appears on the screen. It commonly have a text message and two buttons which could be Yes or No, Accept or Dismiss, Ok or Cancel.




2.2. How to Handle an Alert with Selenium?

We already know that there aren't much operations we can perform on an alert. There is an Alert class in Selenium WebDriver, all the alert handling commands are present inside that class. We have to create the object of Alert class and then we can call those commands to handle alerts. Below is the syntax how to use those commands to handle web alerts:

Syntax:

/*  Alert handling   */

/* Alert class object creation
 * And switches the control/focus of your execution to the alert 
 */
Alert alert = driver.switchTo().alert();

// Below command is used to accept the alert 
// like click on Yes, Accept, Ok button
alert.accept();

// Below command is used to dismiss/reject the alert 
// like click on No, Dismiss, Cancel button
alert.dismiss();

Code Explanation:
  1. First of all we have created the object of Alert class and named it as 'alert'. And on the right side of '=' we are switching the focus of the WebDriver execution to the alert so that the next commands could be performed on the alert and not on the web page present below the alert.
  2. alert.accept() command is to accept any alert. Like if we want to click on the Yes, Accept or Confirm button on any alert then we'll use this command.
  3. alert.dismiss() command is used to dismiss an alert. Like if you want to click on No, Cancel, Dismiss button on any alert then we'll use this command.

2.3. How to Validate Alert message?

Apart from clicking on the OK or Cancel buttons another action which needs to be performed on an alert while automating is to validate the message displayed on the alert. We have the alert.getText() command in Alert class which can be used to validate alert message.

Example Code to Validate Alert message/text:

/*  Validate Alert Message with Selenium WebDriver   */

/* Alert class object creation
 * And switches the control/focus of your execution to the alert 
 */
Alert alert = driver.switchTo().alert();

// Expected Text
String expectedPopUpText = "Congratulations!";

// Expected text - getText() is the command to get text from a pop-up
String actualPopUpText = alert.getText();

// Print pop up text value before validation
System.out.println(actualPopUpText);

// Validate text
if expectedPopUpText == actualPopUpText){
    System.out.println("Pop Up Text matched.");
}
else{
    System.out.println("Pop Up Text does not matched.");
}

Code Explanation:
  1. Declare a string and initialize it with expected message value.
  2. Create and initialize Alert class object named as 'alert'.
  3. Get the value of the text message from the alert using getText() command.
  4. Print the text value.
  5. Match the value with the expected value using if/else condition and print the success or failure message.

Dynamic Web Table Handling in Selenium << Previous     ||     Next >>   Selenium with TestNG Tutorial


Author
Passionately working as an Automation Developer from more than a decade. Let's connect LinkedIn.

Follow Us

YouTube Channel | Facebook Page | Telegram Channel | Quora Space
Feel free to ask queries or share your thoughts in comments or email us.

Comments

Popular posts from this blog

10+ Best Demo Websites for Selenium Automation Testing Practice

Automate Amazon like E-Commerce Website with Selenium WebDriver

Handle Static and Dynamic Web Table in Selenium WebDriver

Top 7 Web Development Trends in 2022

How to Automate Google Search with Selenium WebDriver

25+ Most Important Selenium WebDriver Commands Tutorial

50+ Most Important Selenium WebDriver Interview Questions and Answers

How to Find Broken Links on Webpage with Selenium WebDriver