Frames and windows
The element is plainly visible on the page, the locator is correct, and findElement still
reports that it does not exist. The element is inside an <iframe>, or on a tab the link just
opened, and WebDriver is still looking at the document it started in.
Recommended approach
WebDriver always has exactly one current browsing context: one window or tab, and within it one frame. Commands only see that context. Switching is explicit, and you are responsible for switching back.
Frames. Locate the <iframe> element like any other element and switch to it. You can also
switch by the frame’s name or id, or by index, but a located element is the least
ambiguous. When you are done, switch to the default content to return to the top-level
document. A frame reference goes stale when the page reloads, so switch again after navigation.
Windows and tabs. Each window or tab has a handle, an opaque string. Record the current
handle before clicking a link that opens a new one, wait until the number of handles grows,
switch to the handle you have not seen before, and switch back to the original handle when
you are finished. WebDriver makes no distinction between a tab and a window. If you just need
a clean tab, open one yourself with newWindow; it is created already switched to.
Closing the current window leaves the session pointing at nothing, so switch to another
handle immediately after close. Call quit, not close, at the end of the test; it closes
every window and ends the session.
Switch into a frame using a located element:
WebElement iframe = driver.findElement(By.id("iframe1"));
//Switch to the frame
driver.switchTo().frame(iframe);/examples/java/src/test/java/dev/selenium/interactions/FramesTest.java
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package dev.selenium.interactions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class FramesTest{
@Test
public void informationWithElements() {
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/iframes.html");
//switch To IFrame using Web Element
WebElement iframe = driver.findElement(By.id("iframe1"));
//Switch to the frame
driver.switchTo().frame(iframe);
assertEquals(true, driver.getPageSource().contains("We Leave From Here"));
//Now we can type text into email field
WebElement emailE = driver.findElement(By.id("email"));
emailE.sendKeys("admin@selenium.dev");
emailE.clear();
driver.switchTo().defaultContent();
//switch To IFrame using name or id
WebElement iframe1=driver.findElement(By.name("iframe1-name"));
//Switch to the frame
driver.switchTo().frame(iframe1);
assertEquals(true, driver.getPageSource().contains("We Leave From Here"));
WebElement email = driver.findElement(By.id("email"));
//Now we can type text into email field
email.sendKeys("admin@selenium.dev");
email.clear();
driver.switchTo().defaultContent();
//switch To IFrame using index
driver.switchTo().frame(0);
assertEquals(true, driver.getPageSource().contains("We Leave From Here"));
//leave frame
driver.switchTo().defaultContent();
assertEquals(true, driver.getPageSource().contains("This page has iframes"));
//quit the browser
driver.quit();
}
}
iframe = driver.find_element(By.ID, "iframe1")
driver.switch_to.frame(iframe)/examples/python/tests/interactions/test_frames.py
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from selenium import webdriver
from selenium.webdriver.common.by import By
#set chrome and launch web page
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/iframes.html")
# --- Switch to iframe using WebElement ---
iframe = driver.find_element(By.ID, "iframe1")
driver.switch_to.frame(iframe)
assert "We Leave From Here" in driver.page_source
email_element = driver.find_element(By.ID, "email")
email_element.send_keys("admin@selenium.dev")
email_element.clear()
driver.switch_to.default_content()
# --- Switch to iframe using name or ID ---
iframe1=driver.find_element(By.NAME, "iframe1-name") # (This line doesn't switch, just locates)
driver.switch_to.frame(iframe1)
assert "We Leave From Here" in driver.page_source
email = driver.find_element(By.ID, "email")
email.send_keys("admin@selenium.dev")
email.clear()
driver.switch_to.default_content()
# --- Switch to iframe using index ---
driver.switch_to.frame(0)
assert "We Leave From Here" in driver.page_source
# --- Final page content check ---
driver.switch_to.default_content()
assert "This page has iframes" in driver.page_source
#quit the driver
driver.quit()
#demo code for conference
IWebElement iframe = driver.FindElement(By.Id("iframe1"));
//Switch to the frame
driver.SwitchTo().Frame(iframe);/examples/dotnet/SeleniumDocs/Interactions/FramesTest.cs
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Collections.Generic;
namespace SeleniumDocs.Interactions
{
[TestClass]
public class FramesTest
{
[TestMethod]
public void TestFrames()
{
WebDriver driver = new ChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
// Navigate to Url
driver.Url= "https://www.selenium.dev/selenium/web/iframes.html";
//switch To IFrame using Web Element
IWebElement iframe = driver.FindElement(By.Id("iframe1"));
//Switch to the frame
driver.SwitchTo().Frame(iframe);
Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));
//Now we can type text into email field
IWebElement emailE = driver.FindElement(By.Id("email"));
emailE.SendKeys("admin@selenium.dev");
emailE.Clear();
driver.SwitchTo().DefaultContent();
//switch To IFrame using name or id
IWebElement iframe1=driver.FindElement(By.Name("iframe1-name"));
//Switch to the frame
driver.SwitchTo().Frame(iframe1);
Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));
IWebElement email = driver.FindElement(By.Id("email"));
//Now we can type text into email field
email.SendKeys("admin@selenium.dev");
email.Clear();
driver.SwitchTo().DefaultContent();
//switch To IFrame using index
driver.SwitchTo().Frame(0);
Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));
//leave frame
driver.SwitchTo().DefaultContent();
Assert.AreEqual(true, driver.PageSource.Contains("This page has iframes"));
//quit the browser
driver.Quit();
}
}
} iframe = driver.find_element(:id, 'iframe1')
driver.switch_to.frame(iframe)/examples/ruby/spec/interactions/frames_spec.rb
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Frames' do
let(:driver) { start_session }
it 'performs iframe switching operations' do
driver.navigate.to 'https://www.selenium.dev/selenium/web/iframes.html'
# --- Switch to iframe using WebElement ---
iframe = driver.find_element(:id, 'iframe1')
driver.switch_to.frame(iframe)
expect(driver.page_source).to include('We Leave From Here')
email_element = driver.find_element(:id, 'email')
email_element.send_keys('admin@selenium.dev')
email_element.clear
driver.switch_to.default_content
# --- Switch to iframe using name or ID ---
iframe1 = driver.find_element(:name, 'iframe1-name')
driver.switch_to.frame(iframe1)
expect(driver.page_source).to include('We Leave From Here')
email = driver.find_element(:id, 'email')
email.send_keys('admin@selenium.dev')
email.clear
driver.switch_to.default_content
# --- Switch to iframe using index ---
driver.switch_to.frame(0)
expect(driver.page_source).to include('We Leave From Here')
# --- Final page content check ---
driver.switch_to.default_content
expect(driver.page_source).to include('This page has iframes')
end
end
Return to the top-level document:
driver.switchTo().defaultContent();/examples/java/src/test/java/dev/selenium/interactions/FramesTest.java
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package dev.selenium.interactions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class FramesTest{
@Test
public void informationWithElements() {
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/iframes.html");
//switch To IFrame using Web Element
WebElement iframe = driver.findElement(By.id("iframe1"));
//Switch to the frame
driver.switchTo().frame(iframe);
assertEquals(true, driver.getPageSource().contains("We Leave From Here"));
//Now we can type text into email field
WebElement emailE = driver.findElement(By.id("email"));
emailE.sendKeys("admin@selenium.dev");
emailE.clear();
driver.switchTo().defaultContent();
//switch To IFrame using name or id
WebElement iframe1=driver.findElement(By.name("iframe1-name"));
//Switch to the frame
driver.switchTo().frame(iframe1);
assertEquals(true, driver.getPageSource().contains("We Leave From Here"));
WebElement email = driver.findElement(By.id("email"));
//Now we can type text into email field
email.sendKeys("admin@selenium.dev");
email.clear();
driver.switchTo().defaultContent();
//switch To IFrame using index
driver.switchTo().frame(0);
assertEquals(true, driver.getPageSource().contains("We Leave From Here"));
//leave frame
driver.switchTo().defaultContent();
assertEquals(true, driver.getPageSource().contains("This page has iframes"));
//quit the browser
driver.quit();
}
}
driver.switch_to.default_content()/examples/python/tests/interactions/test_frames.py
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from selenium import webdriver
from selenium.webdriver.common.by import By
#set chrome and launch web page
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/iframes.html")
# --- Switch to iframe using WebElement ---
iframe = driver.find_element(By.ID, "iframe1")
driver.switch_to.frame(iframe)
assert "We Leave From Here" in driver.page_source
email_element = driver.find_element(By.ID, "email")
email_element.send_keys("admin@selenium.dev")
email_element.clear()
driver.switch_to.default_content()
# --- Switch to iframe using name or ID ---
iframe1=driver.find_element(By.NAME, "iframe1-name") # (This line doesn't switch, just locates)
driver.switch_to.frame(iframe1)
assert "We Leave From Here" in driver.page_source
email = driver.find_element(By.ID, "email")
email.send_keys("admin@selenium.dev")
email.clear()
driver.switch_to.default_content()
# --- Switch to iframe using index ---
driver.switch_to.frame(0)
assert "We Leave From Here" in driver.page_source
# --- Final page content check ---
driver.switch_to.default_content()
assert "This page has iframes" in driver.page_source
#quit the driver
driver.quit()
#demo code for conference
driver.SwitchTo().DefaultContent();/examples/dotnet/SeleniumDocs/Interactions/FramesTest.cs
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Collections.Generic;
namespace SeleniumDocs.Interactions
{
[TestClass]
public class FramesTest
{
[TestMethod]
public void TestFrames()
{
WebDriver driver = new ChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
// Navigate to Url
driver.Url= "https://www.selenium.dev/selenium/web/iframes.html";
//switch To IFrame using Web Element
IWebElement iframe = driver.FindElement(By.Id("iframe1"));
//Switch to the frame
driver.SwitchTo().Frame(iframe);
Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));
//Now we can type text into email field
IWebElement emailE = driver.FindElement(By.Id("email"));
emailE.SendKeys("admin@selenium.dev");
emailE.Clear();
driver.SwitchTo().DefaultContent();
//switch To IFrame using name or id
IWebElement iframe1=driver.FindElement(By.Name("iframe1-name"));
//Switch to the frame
driver.SwitchTo().Frame(iframe1);
Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));
IWebElement email = driver.FindElement(By.Id("email"));
//Now we can type text into email field
email.SendKeys("admin@selenium.dev");
email.Clear();
driver.SwitchTo().DefaultContent();
//switch To IFrame using index
driver.SwitchTo().Frame(0);
Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));
//leave frame
driver.SwitchTo().DefaultContent();
Assert.AreEqual(true, driver.PageSource.Contains("This page has iframes"));
//quit the browser
driver.Quit();
}
}
} driver.switch_to.default_content/examples/ruby/spec/interactions/frames_spec.rb
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Frames' do
let(:driver) { start_session }
it 'performs iframe switching operations' do
driver.navigate.to 'https://www.selenium.dev/selenium/web/iframes.html'
# --- Switch to iframe using WebElement ---
iframe = driver.find_element(:id, 'iframe1')
driver.switch_to.frame(iframe)
expect(driver.page_source).to include('We Leave From Here')
email_element = driver.find_element(:id, 'email')
email_element.send_keys('admin@selenium.dev')
email_element.clear
driver.switch_to.default_content
# --- Switch to iframe using name or ID ---
iframe1 = driver.find_element(:name, 'iframe1-name')
driver.switch_to.frame(iframe1)
expect(driver.page_source).to include('We Leave From Here')
email = driver.find_element(:id, 'email')
email.send_keys('admin@selenium.dev')
email.clear
driver.switch_to.default_content
# --- Switch to iframe using index ---
driver.switch_to.frame(0)
expect(driver.page_source).to include('We Leave From Here')
# --- Final page content check ---
driver.switch_to.default_content
expect(driver.page_source).to include('This page has iframes')
end
end
Follow a link into a new window and switch to it:
//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);/examples/java/src/test/java/dev/selenium/interactions/WindowsTest.java
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
}
} original_window_handle = driver.current_window_handle
driver.find_element(By.LINK_TEXT, "Open new window").click()
wait.until(EC.number_of_windows_to_be(2))
new_window_handle = (set(driver.window_handles) - {original_window_handle}).pop()
driver.switch_to.window(new_window_handle)/examples/python/tests/interactions/test_windows.py
import pytest
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
url = "https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html"
@pytest.fixture()
def driver():
driver = webdriver.Chrome()
yield driver
driver.quit()
def test_current_window_handle(driver):
driver.get(url)
current_handle = driver.current_window_handle
assert current_handle is not None
def test_switch_to_window(driver):
driver.get(url)
wait = WebDriverWait(driver, 10)
original_window_handle = driver.current_window_handle
driver.find_element(By.LINK_TEXT, "Open new window").click()
wait.until(EC.number_of_windows_to_be(2))
new_window_handle = (set(driver.window_handles) - {original_window_handle}).pop()
driver.switch_to.window(new_window_handle)
assert driver.current_window_handle == new_window_handle
def test_close_window(driver):
driver.get(url)
wait = WebDriverWait(driver, 10)
original_window_handle = driver.current_window_handle
driver.find_element(By.LINK_TEXT, "Open new window").click()
wait.until(EC.number_of_windows_to_be(2))
new_window_handle = (set(driver.window_handles) - {original_window_handle}).pop()
driver.switch_to.window(new_window_handle)
driver.close()
driver.switch_to.window(original_window_handle)
assert driver.current_window_handle == original_window_handle
assert len(driver.window_handles) == 1
def test_create_new_window(driver):
# Opens a new tab and switches to new tab
driver.switch_to.new_window('tab')
assert driver.title == ""
# Opens a new window and switches to new window
driver.switch_to.new_window('window')
assert driver.title == "" //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);/examples/dotnet/SeleniumDocs/Interactions/WindowsTest.cs
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
}
}
}
Open a fresh tab and switch to it in one step:
driver.switch_to.new_window(:tab)/examples/ruby/spec/interactions/windows_spec.rb
# frozen_string_literal: true
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
await driver.switchTo().newWindow('tab');/examples/javascript/test/interactions/windows.spec.js
const {Builder, By} = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
const assert = require("node:assert");
let opts = new chrome.Options();
opts.addArguments('--headless');
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let imgMagicNumber = 'iVBOR'
let base64Code
describe('Interactions - Windows', function () {
let driver;
before(async function () {
driver = await new Builder().forBrowser('chrome').setChromeOptions(opts).build();
});
after(async () => await driver.quit());
it('Should be able to print page to pdf', async function () {
await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
let base64 = await driver.printPage({pageRanges: ["1-2"]});
// page can be saved as a PDF as below
// await fs.writeFileSync('./test.pdf', base64, 'base64');
base64Code = base64.slice(startIndex, endIndex)
assert.strictEqual(base64Code, pdfMagicNumber)
});
it('Should be able to get text using executeScript', async function () {
await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');
// Stores the header element
let header = await driver.findElement(By.css('h1'));
// Executing JavaScript to capture innerText of header element
let text = await driver.executeScript('return arguments[0].innerText', header);
assert.strictEqual(text, `Type Stuff`)
});
it('Should be able to take Element Screenshot', async function () {
await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');
let header = await driver.findElement(By.css('h1'));
// Captures the element screenshot
let encodedString = await header.takeScreenshot(true);
// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)
});
it('Should be able to takeScreenshot', async function () {
await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');
// Captures the screenshot
let encodedString = await driver.takeScreenshot();
// save screenshot as below
// await fs.writeFileSync('./image.png', encodedString, 'base64');
base64Code = encodedString.slice(startIndex, endIndex)
assert.strictEqual(base64Code, imgMagicNumber)
});
it('Should be able to switch to newWindow and newTab and close', async function () {
await driver.get('https://www.selenium.dev/selenium/web/');
const initialWindow = await driver.getAllWindowHandles();
assert.strictEqual(initialWindow.length, 1)
// Opens a new tab and switches to new tab
await driver.switchTo().newWindow('tab');
const browserTabs = await driver.getAllWindowHandles();
assert.strictEqual(browserTabs.length, 2)
// Opens a new window and switches to new window
await driver.switchTo().newWindow('window');
const windows = await driver.getAllWindowHandles();
assert.strictEqual(windows.length, 3)
//Close the tab or window
await driver.close();
//Switch back to the old tab or window
await driver.switchTo().window(windows[1]);
const windowsAfterClose = await driver.getAllWindowHandles();
assert.strictEqual(windowsAfterClose.length, 2);
});
it('Should be able to getWindow Size', async function () {
await driver.get('https://www.selenium.dev/selenium/web/');
// Access each dimension individually
const { width, height } = await driver.manage().window().getRect();
// Or store the dimensions and query them later
const rect = await driver.manage().window().getRect();
const windowWidth = rect.width;
const windowHeight = rect.height;
assert.ok(windowWidth>0);
assert.ok(windowHeight>0);
});
it('Should be able to getWindow position', async function () {
await driver.get('https://www.selenium.dev/selenium/web/');
// Access each dimension individually
const { x, y } = await driver.manage().window().getRect();
// Or store the dimensions and query them later
const rect = await driver.manage().window().getRect();
const x1 = rect.x;
const y1 = rect.y;
assert.ok(x1>=0);
assert.ok(y1>=0);
});
});Common errors
- NoSuchElementException: the element exists but in a different frame or window from the current one.
- NoSuchFrameException: the frame name, id or index did not match, or the frame was removed by a navigation.
- NoSuchWindowException: the window you were in was closed. Switch to a handle that still exists.
- StaleElementReferenceException: an element from the old frame or page is being used after a switch or reload.
Reference
- Working with iframes and frames
- Working with windows and tabs
- BiDi browsing context: creating, inspecting and closing contexts with events



