Working with windows and tabs

Windows and tabs

Get window handle

WebDriver does not make the distinction between windows and tabs. If your site opens a new tab or window, Selenium will let you work with it using a window handle. Each window has a unique identifier which remains persistent in a single session. You can get the window handle of the current window by using:

Move Code

15
21
Show full example
package dev.selenium.interactions;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class WindowsTest {

    @Test
    public void windowsExampleCode() {
        
    	WebDriver driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
        // Navigate to Url
        driver.get("https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html");
        //fetch handle of this
        String currHandle=driver.getWindowHandle();
        assertNotNull(currHandle);
        
        //click on link to open a new window
        driver.findElement(By.linkText("Open new window")).click();
        //fetch handles of all windows, there will be two, [0]- default, [1] - new window
        Object[] windowHandles=driver.getWindowHandles().toArray();
        driver.switchTo().window((String) windowHandles[1]);
        //assert on title of new window
        String title=driver.getTitle();
        assertEquals("Simple Page",title);
        
        //closing current window
        driver.close();
        //Switch back to the old tab or window
        driver.switchTo().window((String) windowHandles[0]);
        
        //Opens a new tab and switches to new tab
        driver.switchTo().newWindow(WindowType.TAB);
        assertEquals("",driver.getTitle());
        
        //Opens a new window and switches to new window
        driver.switchTo().newWindow(WindowType.WINDOW);
        assertEquals("",driver.getTitle());
             
        //quitting driver
        driver.quit(); //close all windows
	   
   	}
}
driver.current_window_handle
16
  22
Show full example
using System;
  using Microsoft.VisualStudio.TestTools.UnitTesting;
  using OpenQA.Selenium;
  using OpenQA.Selenium.Chrome;
  using System.Collections.Generic;
  namespace SeleniumDocs.Interactions
  {
      [TestClass]
      public class WindowsTest
      {
          [TestMethod]
          public void TestWindowCommands()
          {
              WebDriver driver = new ChromeDriver();
              driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
  
              // Navigate to Url
              driver.Url="https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html";
              //fetch handle of this
              String currHandle = driver.CurrentWindowHandle;
              Assert.IsNotNull(currHandle);
  
              //click on link to open a new window
              driver.FindElement(By.LinkText("Open new window")).Click();
              //fetch handles of all windows, there will be two, [0]- default, [1] - new window
              IList<string> windowHandles = new List<string>(driver.WindowHandles);
              driver.SwitchTo().Window(windowHandles[1]);
              //assert on title of new window
              String title = driver.Title;
              Assert.AreEqual("Simple Page", title);
  
              //closing current window
              driver.Close();
              //Switch back to the old tab or window
              driver.SwitchTo().Window(windowHandles[0]);
  
              //Opens a new tab and switches to new tab
              driver.SwitchTo().NewWindow(WindowType.Tab);
              Assert.AreEqual("", driver.Title);
  
              //Opens a new window and switches to new window
              driver.SwitchTo().NewWindow(WindowType.Window);
              Assert.AreEqual("", driver.Title);
  
              //quitting driver
              driver.Quit(); //close all windows
          }
      }
  }
  
driver.window_handle
await driver.getWindowHandle();
driver.windowHandle

Switching windows or tabs

Clicking a link which opens in a new window will focus the new window or tab on screen, but WebDriver will not know which window the Operating System considers active. To work with the new window you will need to switch to it. For this, we fetch all window handles, and store them in an array. The array position fills in the order the window is launched. So first position will be default browser, and so on.

Move Code

21
30
Show full example
package dev.selenium.interactions;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class WindowsTest {

    @Test
    public void windowsExampleCode() {
        
    	WebDriver driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
        // Navigate to Url
        driver.get("https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html");
        //fetch handle of this
        String currHandle=driver.getWindowHandle();
        assertNotNull(currHandle);
        
        //click on link to open a new window
        driver.findElement(By.linkText("Open new window")).click();
        //fetch handles of all windows, there will be two, [0]- default, [1] - new window
        Object[] windowHandles=driver.getWindowHandles().toArray();
        driver.switchTo().window((String) windowHandles[1]);
        //assert on title of new window
        String title=driver.getTitle();
        assertEquals("Simple Page",title);
        
        //closing current window
        driver.close();
        //Switch back to the old tab or window
        driver.switchTo().window((String) windowHandles[0]);
        
        //Opens a new tab and switches to new tab
        driver.switchTo().newWindow(WindowType.TAB);
        assertEquals("",driver.getTitle());
        
        //Opens a new window and switches to new window
        driver.switchTo().newWindow(WindowType.WINDOW);
        assertEquals("",driver.getTitle());
             
        //quitting driver
        driver.quit(); //close all windows
	   
   	}
}
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

with webdriver.Firefox() as driver:
    # Open URL
    driver.get("https://seleniumhq.github.io")

    # Setup wait for later
    wait = WebDriverWait(driver, 10)

    # Store the ID of the original window
    original_window = driver.current_window_handle

    # Check we don't have other windows open already
    assert len(driver.window_handles) == 1

    # Click the link which opens in a new window
    driver.find_element(By.LINK_TEXT, "new window").click()

    # Wait for the new window or tab
    wait.until(EC.number_of_windows_to_be(2))

    # Loop through until we find a new window handle
    for window_handle in driver.window_handles:
        if window_handle != original_window:
            driver.switch_to.window(window_handle)
            break

    # Wait for the new tab to finish loading content
    wait.until(EC.title_is("SeleniumHQ Browser Automation"))
  
22
  31
Show full example
using System;
  using Microsoft.VisualStudio.TestTools.UnitTesting;
  using OpenQA.Selenium;
  using OpenQA.Selenium.Chrome;
  using System.Collections.Generic;
  namespace SeleniumDocs.Interactions
  {
      [TestClass]
      public class WindowsTest
      {
          [TestMethod]
          public void TestWindowCommands()
          {
              WebDriver driver = new ChromeDriver();
              driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
  
              // Navigate to Url
              driver.Url="https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html";
              //fetch handle of this
              String currHandle = driver.CurrentWindowHandle;
              Assert.IsNotNull(currHandle);
  
              //click on link to open a new window
              driver.FindElement(By.LinkText("Open new window")).Click();
              //fetch handles of all windows, there will be two, [0]- default, [1] - new window
              IList<string> windowHandles = new List<string>(driver.WindowHandles);
              driver.SwitchTo().Window(windowHandles[1]);
              //assert on title of new window
              String title = driver.Title;
              Assert.AreEqual("Simple Page", title);
  
              //closing current window
              driver.Close();
              //Switch back to the old tab or window
              driver.SwitchTo().Window(windowHandles[0]);
  
              //Opens a new tab and switches to new tab
              driver.SwitchTo().NewWindow(WindowType.Tab);
              Assert.AreEqual("", driver.Title);
  
              //Opens a new window and switches to new window
              driver.SwitchTo().NewWindow(WindowType.Window);
              Assert.AreEqual("", driver.Title);
  
              //quitting driver
              driver.Quit(); //close all windows
          }
      }
  }
  
    # Store the ID of the original window
original_window = driver.window_handle

    # Check we don't have other windows open already
assert(driver.window_handles.length == 1, 'Expected one window')

    # Click the link which opens in a new window
driver.find_element(link: 'new window').click

    # Wait for the new window or tab
wait.until { driver.window_handles.length == 2 }

    #Loop through until we find a new window handle
driver.window_handles.each do |handle|
    if handle != original_window
        driver.switch_to.window handle
        break
    end
end

    #Wait for the new tab to finish loading content
wait.until { driver.title == 'Selenium documentation'}
  
//Store the ID of the original window
const originalWindow = await driver.getWindowHandle();

//Check we don't have other windows open already
assert((await driver.getAllWindowHandles()).length === 1);

//Click the link which opens in a new window
await driver.findElement(By.linkText('new window')).click();

//Wait for the new window or tab
await driver.wait(
    async () => (await driver.getAllWindowHandles()).length === 2,
    10000
  );

//Loop through until we find a new window handle
const windows = await driver.getAllWindowHandles();
windows.forEach(async handle => {
  if (handle !== originalWindow) {
    await driver.switchTo().window(handle);
  }
});

//Wait for the new tab to finish loading content
await driver.wait(until.titleIs('Selenium documentation'), 10000);
  
//Store the ID of the original window
val originalWindow = driver.getWindowHandle()

//Check we don't have other windows open already
assert(driver.getWindowHandles().size() === 1)

//Click the link which opens in a new window
driver.findElement(By.linkText("new window")).click()

//Wait for the new window or tab
wait.until(numberOfWindowsToBe(2))

//Loop through until we find a new window handle
for (windowHandle in driver.getWindowHandles()) {
    if (!originalWindow.contentEquals(windowHandle)) {
        driver.switchTo().window(windowHandle)
        break
    }
}

//Wait for the new tab to finish loading content
wait.until(titleIs("Selenium documentation"))

  

Closing a window or tab

When you are finished with a window or tab and it is not the last window or tab open in your browser, you should close it and switch back to the window you were using previously. Assuming you followed the code sample in the previous section you will have the previous window handle stored in a variable. Put this together and you will get:

Move Code

30
35
Show full example
package dev.selenium.interactions;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class WindowsTest {

    @Test
    public void windowsExampleCode() {
        
    	WebDriver driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
        // Navigate to Url
        driver.get("https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html");
        //fetch handle of this
        String currHandle=driver.getWindowHandle();
        assertNotNull(currHandle);
        
        //click on link to open a new window
        driver.findElement(By.linkText("Open new window")).click();
        //fetch handles of all windows, there will be two, [0]- default, [1] - new window
        Object[] windowHandles=driver.getWindowHandles().toArray();
        driver.switchTo().window((String) windowHandles[1]);
        //assert on title of new window
        String title=driver.getTitle();
        assertEquals("Simple Page",title);
        
        //closing current window
        driver.close();
        //Switch back to the old tab or window
        driver.switchTo().window((String) windowHandles[0]);
        
        //Opens a new tab and switches to new tab
        driver.switchTo().newWindow(WindowType.TAB);
        assertEquals("",driver.getTitle());
        
        //Opens a new window and switches to new window
        driver.switchTo().newWindow(WindowType.WINDOW);
        assertEquals("",driver.getTitle());
             
        //quitting driver
        driver.quit(); //close all windows
	   
   	}
}
    #Close the tab or window
driver.close()

    #Switch back to the old tab or window
driver.switch_to.window(original_window)
  
31
  36
Show full example
using System;
  using Microsoft.VisualStudio.TestTools.UnitTesting;
  using OpenQA.Selenium;
  using OpenQA.Selenium.Chrome;
  using System.Collections.Generic;
  namespace SeleniumDocs.Interactions
  {
      [TestClass]
      public class WindowsTest
      {
          [TestMethod]
          public void TestWindowCommands()
          {
              WebDriver driver = new ChromeDriver();
              driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
  
              // Navigate to Url
              driver.Url="https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html";
              //fetch handle of this
              String currHandle = driver.CurrentWindowHandle;
              Assert.IsNotNull(currHandle);
  
              //click on link to open a new window
              driver.FindElement(By.LinkText("Open new window")).Click();
              //fetch handles of all windows, there will be two, [0]- default, [1] - new window
              IList<string> windowHandles = new List<string>(driver.WindowHandles);
              driver.SwitchTo().Window(windowHandles[1]);
              //assert on title of new window
              String title = driver.Title;
              Assert.AreEqual("Simple Page", title);
  
              //closing current window
              driver.Close();
              //Switch back to the old tab or window
              driver.SwitchTo().Window(windowHandles[0]);
  
              //Opens a new tab and switches to new tab
              driver.SwitchTo().NewWindow(WindowType.Tab);
              Assert.AreEqual("", driver.Title);
  
              //Opens a new window and switches to new window
              driver.SwitchTo().NewWindow(WindowType.Window);
              Assert.AreEqual("", driver.Title);
  
              //quitting driver
              driver.Quit(); //close all windows
          }
      }
  }
  
    #Close the tab or window
driver.close

    #Switch back to the old tab or window
driver.switch_to.window original_window
  
//Close the tab or window
await driver.close();

//Switch back to the old tab or window
await driver.switchTo().window(originalWindow);
  
//Close the tab or window
driver.close()

//Switch back to the old tab or window
driver.switchTo().window(originalWindow)

  

Forgetting to switch back to another window handle after closing a window will leave WebDriver executing on the now closed page, and will trigger a No Such Window Exception. You must switch back to a valid window handle in order to continue execution.

Create new window (or) new tab and switch

Creates a new window (or) tab and will focus the new window or tab on screen. You don’t need to switch to work with the new window (or) tab. If you have more than two windows (or) tabs opened other than the new window, you can loop over both windows or tabs that WebDriver can see, and switch to the one which is not the original.

Note: This feature works with Selenium 4 and later versions.

Move Code

35
43
Show full example
package dev.selenium.interactions;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class WindowsTest {

    @Test
    public void windowsExampleCode() {
        
    	WebDriver driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
        // Navigate to Url
        driver.get("https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html");
        //fetch handle of this
        String currHandle=driver.getWindowHandle();
        assertNotNull(currHandle);
        
        //click on link to open a new window
        driver.findElement(By.linkText("Open new window")).click();
        //fetch handles of all windows, there will be two, [0]- default, [1] - new window
        Object[] windowHandles=driver.getWindowHandles().toArray();
        driver.switchTo().window((String) windowHandles[1]);
        //assert on title of new window
        String title=driver.getTitle();
        assertEquals("Simple Page",title);
        
        //closing current window
        driver.close();
        //Switch back to the old tab or window
        driver.switchTo().window((String) windowHandles[0]);
        
        //Opens a new tab and switches to new tab
        driver.switchTo().newWindow(WindowType.TAB);
        assertEquals("",driver.getTitle());
        
        //Opens a new window and switches to new window
        driver.switchTo().newWindow(WindowType.WINDOW);
        assertEquals("",driver.getTitle());
             
        //quitting driver
        driver.quit(); //close all windows
	   
   	}
}
    # Opens a new tab and switches to new tab
driver.switch_to.new_window('tab')

    # Opens a new window and switches to new window
driver.switch_to.new_window('window')
  
36
  44
Show full example
using System;
  using Microsoft.VisualStudio.TestTools.UnitTesting;
  using OpenQA.Selenium;
  using OpenQA.Selenium.Chrome;
  using System.Collections.Generic;
  namespace SeleniumDocs.Interactions
  {
      [TestClass]
      public class WindowsTest
      {
          [TestMethod]
          public void TestWindowCommands()
          {
              WebDriver driver = new ChromeDriver();
              driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
  
              // Navigate to Url
              driver.Url="https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html";
              //fetch handle of this
              String currHandle = driver.CurrentWindowHandle;
              Assert.IsNotNull(currHandle);
  
              //click on link to open a new window
              driver.FindElement(By.LinkText("Open new window")).Click();
              //fetch handles of all windows, there will be two, [0]- default, [1] - new window
              IList<string> windowHandles = new List<string>(driver.WindowHandles);
              driver.SwitchTo().Window(windowHandles[1]);
              //assert on title of new window
              String title = driver.Title;
              Assert.AreEqual("Simple Page", title);
  
              //closing current window
              driver.Close();
              //Switch back to the old tab or window
              driver.SwitchTo().Window(windowHandles[0]);
  
              //Opens a new tab and switches to new tab
              driver.SwitchTo().NewWindow(WindowType.Tab);
              Assert.AreEqual("", driver.Title);
  
              //Opens a new window and switches to new window
              driver.SwitchTo().NewWindow(WindowType.Window);
              Assert.AreEqual("", driver.Title);
  
              //quitting driver
              driver.Quit(); //close all windows
          }
      }
  }
  

Opens a new tab and switches to new tab:

8
10
<details class="mt-3">
  <summary>Show full example</summary>
  <div class="pt-2">
    <div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-rb" data-lang="rb"><span style="display:flex;"><span><span style="color:#8f5902;font-style:italic"># frozen_string_literal: true</span>

require 'spec_helper' RSpec.describe 'Windows' do let(:driver) { start_session } it 'opens new tab' do driver.switch_to.new_window(:tab) expect(driver.window_handles.size).to eq 2 end it 'opens new window' do driver.switch_to.new_window(:window) expect(driver.window_handles.size).to eq 2 end end

<div class="text-end pb-2 mt-2">
  <a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/ruby/spec/interactions/windows_spec.rb#L9" target="_blank">
    <i class="fas fa-external-link-alt pl-2"></i>
    <strong>View full example on GitHub</strong>
  </a>
</div>

Opens a new window and switches to new window:

14
16
<details class="mt-3">
  <summary>Show full example</summary>
  <div class="pt-2">
    <div class="highlight"><pre tabindex="0" style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-rb" data-lang="rb"><span style="display:flex;"><span><span style="color:#8f5902;font-style:italic"># frozen_string_literal: true</span>

require 'spec_helper' RSpec.describe 'Windows' do let(:driver) { start_session } it 'opens new tab' do driver.switch_to.new_window(:tab) expect(driver.window_handles.size).to eq 2 end it 'opens new window' do driver.switch_to.new_window(:window) expect(driver.window_handles.size).to eq 2 end end

<div class="text-end pb-2 mt-2">
  <a href="https://github.com/SeleniumHQ/seleniumhq.github.io/blob/display_full//examples/ruby/spec/interactions/windows_spec.rb#L15" target="_blank">
    <i class="fas fa-external-link-alt pl-2"></i>
    <strong>View full example on GitHub</strong>
  </a>
</div>