Selenium WebDriver: Open Multiple Windows Or Tabs

There are three methods to open multiple windows or tabs in selenium. 

  1. Use different webdriver object, each object open one browser.
  2. Use one webdriver to open multiple browser windows.
  3. Use one webdriver to open multiple tabs.

The first method will cost too much resource. So we will only use the last two methods.

1. Open Multiple Windows Use One WebDriver Object.

  1. Execute javascript code window.open(url) to open a new browser window.
  2. We will open 6 windows in the below java example code.
  3. Handle all the opened windows in java code.
  4. Use the code WebDriver.switchTo().window(String windowHandler) to switch between them.
  5. Change the second browser window’s URL to http://www.google.com.
  6. Close the first browser window.
  7. You can get the detailed source code in the method openSameUrlInMultipleWindow() in section 3.

2. Open Multiple Tabs Use One WebDriver Object.

  1. Find Html body web element.
  2. Send "Ctrl+t" command to body element to open a new browser tab.
  3. Send "Ctrl+2" command to navigate to the second browser tab.
  4. Change the URL to google.com for the second browser tab.
  5. Get the body web element in the second browser tab.
  6. Send "Ctrl+3" command to navigate to the third browser tab.
  7. Send "Ctrl+w" command to close the third browser tab.
  8. You can get the detailed source code in the method openSameUrlInMultipleTab() in section 3.

3. Use WebDriver To Open Multiple Browser Windows Or Tabs Source Code.

Below is the full source code that implements open multiple browser windows of tabs use selenium webdriver. The Firefox browser’s initiate and destroy are implemented in the @BeforeClass method and @AfterClass method. The below java code can be run in TestNG.

package com.dev2qa.webdriver;

import java.util.Iterator;
import java.util.Set;

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.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class TestOpenSamePageUrlInMultipleWindow {
    
      private static WebDriver ffDriver = null;
        
      @BeforeClass
      public void beforeClass() {
            if(ffDriver==null)
            {
                ffDriver = new FirefoxDriver();
                /* Maximize the Firefox browser window. */
                ffDriver.manage().window().maximize();
            }
      }

      @AfterClass
      public void afterClass() {
          if(ffDriver != null)
            {
                /* quit() method will close all Firefox browser window. */
                ffDriver.quit();
            }
      }
    
      @Test
      public void openSameUrlInMultipleWindow() throws InterruptedException {
          
          String pageUrl = "http://www.bing.com";
          this.ffDriver.get(pageUrl);
          
          /* Cast webdriver object to Javascript Executor object. */
          JavascriptExecutor jsExecutor = (JavascriptExecutor)this.ffDriver;
          
          /* Javascript that will create new Firefox window. */
          String jsOpenNewWindow = "window.open('"+pageUrl+"');";
          /* Run above javascript. */
          for(int i=0;i<6;i++)
          {
              jsExecutor.executeScript(jsOpenNewWindow);
              Thread.sleep(1000);
              System.out.println("One window opennd.");
          }
          
          Set<String> windowHandleSet = this.ffDriver.getWindowHandles();
          if(windowHandleSet!=null)
          {
              Iterator<String> it = windowHandleSet.iterator();
              
              int i = 0;
              while(it.hasNext())
              {
                  String windowHandleStr = it.next();
                  System.out.println("Window Handler String : " + windowHandleStr);
                  
                  /* Change the third Firefox window page url to http://www.quora.com*/
                  if(i==2)
                  {
                      this.ffDriver.switchTo().window(windowHandleStr);
                      this.ffDriver.get("http://www.google.com");
                      System.out.println("Switch window " + windowHandleStr + " to http://www.google.com");
                      Thread.sleep(3000);
                  }
                  i++;
                  
                  /* Close the first Firefox window. */
                  if(i==1)
                  {
                      this.ffDriver.switchTo().window(windowHandleStr);
                      /*Only close current Firefox window.*/
                      this.ffDriver.close();
                      System.out.println("Close window " + windowHandleStr);
                      Thread.sleep(3000);
                  }
              }  
          }
      }
      
      @Test
      public void openSameUrlInMultipleTab() throws InterruptedException {
          
          String pageUrl = "http://www.bing.com";
          this.ffDriver.get(pageUrl);
          
          String currWindowHandleStr = this.ffDriver.getWindowHandle();
          System.out.println("Current window before create tab : " + currWindowHandleStr);
          
          /* Get html body webelement. */
          WebElement bodyElement = this.ffDriver.findElement(By.tagName("body"));
         
          /* Send Ctrl+t to create new tab. */
          for(int i=0;i<6;i++)
          {
              bodyElement.sendKeys(Keys.CONTROL + "t");
              Thread.sleep(1000);
              System.out.println("Open a new tab.");
          }
          
         
          /* Change tab 2 's page url tp http://www.google.com */
          bodyElement.sendKeys(Keys.CONTROL+"2");
          this.ffDriver.get("http://www.google.com");
          Thread.sleep(3000);
          
          currWindowHandleStr = this.ffDriver.getWindowHandle();
          System.out.println("Current window after go to tab 2 : " + currWindowHandleStr);
          
          /* Close tab 3.*/
          /* First need to find the body web element in current tab. */
          bodyElement = this.ffDriver.findElement(By.tagName("body"));
          /* Go to tab 3. */
          bodyElement.sendKeys(Keys.CONTROL+"3");
          this.ffDriver.get("http://www.twitter.com");
          Thread.sleep(3000);
          /* Close current tab. */
          bodyElement.sendKeys(Keys.CONTROL+"w");
          Thread.sleep(3000);
      }
  
}

4. How to use python + selenium to open multiple tabs in a web browser.

  1. I use python code to invoke selenium webdriver. And I want to open multiple web browser tabs in my python source code. Because if I open a new web page by creating a new webdriver instance in python, it will cost so much more time than expected.
  2. In python, it is similar to java, you can use the Control + T ( Windows, Linux )/ Command + T (macOS) to open a web browser tab, and use the Control + W ( Windows, Linux )/ Command + W (macOS) to close a web browser tab. Below is the python source code that can open & close web browser tabs with selenium webdriver.
    # Import selenium webdriver module.
    from selenium import webdriver
    
    # Import selenium webdriver keyboard keys module.
    from selenium.webdriver.common.keys import Keys
    
    # Create an instance of Firefox driver.
    ff_driver = webdriver.Firefox()
    
    # Define a page url.
    page_url = "http://www.google.com"
    
    # Open a tab to display the above web page by URL.
    ff_driver.get(page_url)
    
    # Open a new web browser tab by send the combination of Keys.COMMAND + 't' keys if your python code is running on macOS, if your python code is running on Windows or Linux, then send the Keys.CONTROL + 't'.
    ff_driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't') 
    
    # Define another web page url.
    another_page_url= "http://www.youtube.com"
    
    # Load the above page in the new web browser tab.
    ff_driver.get(another_page_url)
    
    # Send the (Keys.COMMAND + 'w') on macOS or (Keys.CONTROL + 'w') on Windows or Linux to close the newly created web browser tab.
    ff_driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 'w') 
    
    # Close the webdriver instance.
    ff_driver.close()

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.