Windows Handling | Multiple windows handling using JavascriptExecutor.

Traversing through multiple windows using ‘JavascriptExecutor’ and selecting user-defined tab window with ‘Title Partial Text’. This process is called multiple windows handling.

               Some times we have to open multiple windows (tabs) as per the requirement and need to switch the control through various tabs to select user defined tab window. For this, we can use partial text from the window title along with the switchTo statement.

Step to handle multiple windows:

  1. Launch the browser and open the main URL(
  2. Now set a keyword for the expected window using a String variable with partial window text on which user wants to navigate.
  3. Now launch five different tab windows with different URLs using JavascriptExecutor
  4. Use ‘Set collection‘ to get the list of all opened window at a time. (Note: A ‘Set collection’ contains no duplicate values in it.)
  5. Now traverse through each window using ‘foreach‘ loop and switchTo statement.
  6. compare the current window title with the expected window title.
  7. Print the complete Title of expected tab window.

Code Example:

import java.util.Set;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
public class HandlingMultipleWindow {

	public static void main(String[] args) throws InterruptedException 
		String Url_1="";
		String Url_2="";
		String Url_3="";
		String Url_4="";
		String Url_5="";
		// Initialze variable with partial text present in the title.
		// This would be case sensitive.
		String targetTabWindowTitle="Contact";
		System.setProperty("", "drivers\\chromedriver.exe");
		WebDriver driver=new ChromeDriver();
		JavascriptExecutor jse= (JavascriptExecutor)driver;
		// Script to launch blank window.
		// jse.executeScript("'about:blank','_blank');");
		// Script to launch more windows with different URLs
		// Getting list of all opened windows
		Set multipleWindows= driver.getWindowHandles();
		// Use 'foreach()' loop to traverse through all windows
		for (String currentWindow : multipleWindows) 
			String currentWindowTitle=driver.getTitle();
		// Compare current window title with expected title.
				System.out.println("Current Window: "+currentWindowTitle);

3288total visits,3visits today

Leave a Reply

Your email address will not be published. Required fields are marked *