Browsing Context
Commands
This section contains the APIs related to browsing context commands.
Open a new window
Creates a new browsing context in a new window.
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
var bidi = await driver.AsBiDiAsync();
var context = (await bidi.BrowsingContext.CreateAsync(ContextType.Window)).Context;
Assert.IsNotNull(context);/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Create.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task OpenNewTab()
{
var bidi = await driver.AsBiDiAsync();
var context = (await bidi.BrowsingContext.CreateAsync(ContextType.Tab)).Context;
Assert.IsNotNull(context);
}
[TestMethod]
public async Task OpenNewWindow()
{
var bidi = await driver.AsBiDiAsync();
var context = (await bidi.BrowsingContext.CreateAsync(ContextType.Window)).Context;
Assert.IsNotNull(context);
}
[TestMethod]
public async Task OpenTabWithReferenceBrowsingContext()
{
var context1 = context;
var context2 = (await context1.BiDi.BrowsingContext.CreateAsync(ContextType.Tab, new() { ReferenceContext = context1 })).Context;
Assert.IsNotNull(context2);
}
[TestMethod]
public async Task OpenWindowWithReferenceBrowsingContext()
{
var context1 = context;
var context2 = (await context1.BiDi.BrowsingContext.CreateAsync(ContextType.Window, new() { ReferenceContext = context1 })).Context;
Assert.IsNotNull(context2);
}
[TestMethod]
public async Task UseExistingWindowHandle()
{
var context = (await bidi.BrowsingContext.GetTreeAsync()).Contexts[0].Context;
Assert.IsNotNull(context);
}
}
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Open a new tab
Creates a new browsing context in a new tab.
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
var bidi = await driver.AsBiDiAsync();
var context = (await bidi.BrowsingContext.CreateAsync(ContextType.Tab)).Context;
Assert.IsNotNull(context);/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Create.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task OpenNewTab()
{
var bidi = await driver.AsBiDiAsync();
var context = (await bidi.BrowsingContext.CreateAsync(ContextType.Tab)).Context;
Assert.IsNotNull(context);
}
[TestMethod]
public async Task OpenNewWindow()
{
var bidi = await driver.AsBiDiAsync();
var context = (await bidi.BrowsingContext.CreateAsync(ContextType.Window)).Context;
Assert.IsNotNull(context);
}
[TestMethod]
public async Task OpenTabWithReferenceBrowsingContext()
{
var context1 = context;
var context2 = (await context1.BiDi.BrowsingContext.CreateAsync(ContextType.Tab, new() { ReferenceContext = context1 })).Context;
Assert.IsNotNull(context2);
}
[TestMethod]
public async Task OpenWindowWithReferenceBrowsingContext()
{
var context1 = context;
var context2 = (await context1.BiDi.BrowsingContext.CreateAsync(ContextType.Window, new() { ReferenceContext = context1 })).Context;
Assert.IsNotNull(context2);
}
[TestMethod]
public async Task UseExistingWindowHandle()
{
var context = (await bidi.BrowsingContext.GetTreeAsync()).Contexts[0].Context;
Assert.IsNotNull(context);
}
}
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Use existing window handle
Creates a browsing context for the existing tab/window to run commands.
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
var context = (await bidi.BrowsingContext.GetTreeAsync()).Contexts[0].Context;
Assert.IsNotNull(context);/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Create.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task OpenNewTab()
{
var bidi = await driver.AsBiDiAsync();
var context = (await bidi.BrowsingContext.CreateAsync(ContextType.Tab)).Context;
Assert.IsNotNull(context);
}
[TestMethod]
public async Task OpenNewWindow()
{
var bidi = await driver.AsBiDiAsync();
var context = (await bidi.BrowsingContext.CreateAsync(ContextType.Window)).Context;
Assert.IsNotNull(context);
}
[TestMethod]
public async Task OpenTabWithReferenceBrowsingContext()
{
var context1 = context;
var context2 = (await context1.BiDi.BrowsingContext.CreateAsync(ContextType.Tab, new() { ReferenceContext = context1 })).Context;
Assert.IsNotNull(context2);
}
[TestMethod]
public async Task OpenWindowWithReferenceBrowsingContext()
{
var context1 = context;
var context2 = (await context1.BiDi.BrowsingContext.CreateAsync(ContextType.Window, new() { ReferenceContext = context1 })).Context;
Assert.IsNotNull(context2);
}
[TestMethod]
public async Task UseExistingWindowHandle()
{
var context = (await bidi.BrowsingContext.GetTreeAsync()).Contexts[0].Context;
Assert.IsNotNull(context);
}
}
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Open a window with a reference browsing context
A reference browsing context is a top-level browsing context. The API allows to pass the reference browsing context, which is used to create a new window. The implementation is operating system specific.
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
var context1 = context;
var context2 = (await context1.BiDi.BrowsingContext.CreateAsync(ContextType.Window, new() { ReferenceContext = context1 })).Context;
Assert.IsNotNull(context2);/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Create.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task OpenNewTab()
{
var bidi = await driver.AsBiDiAsync();
var context = (await bidi.BrowsingContext.CreateAsync(ContextType.Tab)).Context;
Assert.IsNotNull(context);
}
[TestMethod]
public async Task OpenNewWindow()
{
var bidi = await driver.AsBiDiAsync();
var context = (await bidi.BrowsingContext.CreateAsync(ContextType.Window)).Context;
Assert.IsNotNull(context);
}
[TestMethod]
public async Task OpenTabWithReferenceBrowsingContext()
{
var context1 = context;
var context2 = (await context1.BiDi.BrowsingContext.CreateAsync(ContextType.Tab, new() { ReferenceContext = context1 })).Context;
Assert.IsNotNull(context2);
}
[TestMethod]
public async Task OpenWindowWithReferenceBrowsingContext()
{
var context1 = context;
var context2 = (await context1.BiDi.BrowsingContext.CreateAsync(ContextType.Window, new() { ReferenceContext = context1 })).Context;
Assert.IsNotNull(context2);
}
[TestMethod]
public async Task UseExistingWindowHandle()
{
var context = (await bidi.BrowsingContext.GetTreeAsync()).Contexts[0].Context;
Assert.IsNotNull(context);
}
}
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Open a tab with a reference browsing context
A reference browsing context is a top-level browsing context. The API allows to pass the reference browsing context, which is used to create a new tab. The implementation is operating system specific.
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
var context1 = context;
var context2 = (await context1.BiDi.BrowsingContext.CreateAsync(ContextType.Tab, new() { ReferenceContext = context1 })).Context;
Assert.IsNotNull(context2);/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Create.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task OpenNewTab()
{
var bidi = await driver.AsBiDiAsync();
var context = (await bidi.BrowsingContext.CreateAsync(ContextType.Tab)).Context;
Assert.IsNotNull(context);
}
[TestMethod]
public async Task OpenNewWindow()
{
var bidi = await driver.AsBiDiAsync();
var context = (await bidi.BrowsingContext.CreateAsync(ContextType.Window)).Context;
Assert.IsNotNull(context);
}
[TestMethod]
public async Task OpenTabWithReferenceBrowsingContext()
{
var context1 = context;
var context2 = (await context1.BiDi.BrowsingContext.CreateAsync(ContextType.Tab, new() { ReferenceContext = context1 })).Context;
Assert.IsNotNull(context2);
}
[TestMethod]
public async Task OpenWindowWithReferenceBrowsingContext()
{
var context1 = context;
var context2 = (await context1.BiDi.BrowsingContext.CreateAsync(ContextType.Window, new() { ReferenceContext = context1 })).Context;
Assert.IsNotNull(context2);
}
[TestMethod]
public async Task UseExistingWindowHandle()
{
var context = (await bidi.BrowsingContext.GetTreeAsync()).Contexts[0].Context;
Assert.IsNotNull(context);
}
}
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Navigate to a URL
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
var info = await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assert.IsNotNull(info);
Assert.IsNotNull(info.Navigation);
StringAssert.Contains(info.Url, "/bidi/logEntryAdded.html");/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Navigate.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task NavigateToUrl()
{
var info = await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assert.IsNotNull(info);
Assert.IsNotNull(info.Navigation);
StringAssert.Contains(info.Url, "/bidi/logEntryAdded.html");
}
[TestMethod]
public async Task NavigateToUrlWithReadinessState()
{
var info = await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
Assert.IsNotNull(info);
Assert.IsNotNull(info.Navigation);
StringAssert.Contains(info.Url, "/bidi/logEntryAdded.html");
}
[TestMethod]
public async Task NavigateBack()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
await context.TraverseHistoryAsync(-1);
var url = await WaitForUrlAsync("about:blank");
Assert.AreEqual("about:blank", url);
}
[TestMethod]
public async Task NavigateForward()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
await context.TraverseHistoryAsync(-1);
await WaitForUrlAsync("about:blank");
await context.TraverseHistoryAsync(1);
var url = await WaitForUrlAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assert.AreEqual("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", url);
}
private async Task<string> WaitForUrlAsync(string expectedUrl)
{
var deadline = DateTime.UtcNow.AddSeconds(5);
string url;
do
{
url = (await context.GetTreeAsync()).Contexts[0].Url;
if (url == expectedUrl) return url;
await Task.Delay(100);
} while (DateTime.UtcNow < deadline);
return url;
}
[TestMethod]
public async Task TraverseHistory()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
await context.TraverseHistoryAsync(-1);
var url = await WaitForUrlAsync("about:blank");
Assert.AreEqual("about:blank", url);
}
}
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Navigate to a URL with readiness state
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
var info = await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
Assert.IsNotNull(info);
Assert.IsNotNull(info.Navigation);
StringAssert.Contains(info.Url, "/bidi/logEntryAdded.html");/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Navigate.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task NavigateToUrl()
{
var info = await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assert.IsNotNull(info);
Assert.IsNotNull(info.Navigation);
StringAssert.Contains(info.Url, "/bidi/logEntryAdded.html");
}
[TestMethod]
public async Task NavigateToUrlWithReadinessState()
{
var info = await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
Assert.IsNotNull(info);
Assert.IsNotNull(info.Navigation);
StringAssert.Contains(info.Url, "/bidi/logEntryAdded.html");
}
[TestMethod]
public async Task NavigateBack()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
await context.TraverseHistoryAsync(-1);
var url = await WaitForUrlAsync("about:blank");
Assert.AreEqual("about:blank", url);
}
[TestMethod]
public async Task NavigateForward()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
await context.TraverseHistoryAsync(-1);
await WaitForUrlAsync("about:blank");
await context.TraverseHistoryAsync(1);
var url = await WaitForUrlAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assert.AreEqual("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", url);
}
private async Task<string> WaitForUrlAsync(string expectedUrl)
{
var deadline = DateTime.UtcNow.AddSeconds(5);
string url;
do
{
url = (await context.GetTreeAsync()).Contexts[0].Url;
if (url == expectedUrl) return url;
await Task.Delay(100);
} while (DateTime.UtcNow < deadline);
return url;
}
[TestMethod]
public async Task TraverseHistory()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
await context.TraverseHistoryAsync(-1);
var url = await WaitForUrlAsync("about:blank");
Assert.AreEqual("about:blank", url);
}
}
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Get browsing context tree
Provides a tree of all browsing contexts descending from the parent browsing context, including the parent browsing context.
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
await context.NavigateAsync("https://www.selenium.dev/selenium/web/iframes.html", new() { Wait = ReadinessState.Complete });
var contexts = (await context.GetTreeAsync()).Contexts;
Assert.AreEqual(1, contexts.Length);
Assert.IsNotNull(contexts[0].Children);
Assert.IsTrue(contexts[0].Children.Value.Length >= 1, "Context should contain iframes as children");/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.GetTree.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System.Linq;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task GetBrowsingContextTree()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/iframes.html", new() { Wait = ReadinessState.Complete });
var contexts = (await context.GetTreeAsync()).Contexts;
Assert.AreEqual(1, contexts.Length);
Assert.IsNotNull(contexts[0].Children);
Assert.IsTrue(contexts[0].Children.Value.Length >= 1, "Context should contain iframes as children");
}
[TestMethod]
public async Task GetBrowsingContextTreeWithDepth()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/iframes.html", new() { Wait = ReadinessState.Complete });
var contexts = (await context.GetTreeAsync(new() { MaxDepth = 0 })).Contexts;
Assert.AreEqual(1, contexts.Length);
Assert.IsNull(contexts[0].Children, "Context should not contain iframes as children since depth is 0");
}
[TestMethod]
public async Task GetAllTopLevelBrowsingContexts()
{
var window = (await bidi.BrowsingContext.CreateAsync(ContextType.Window)).Context;
var contexts = (await bidi.BrowsingContext.GetTreeAsync()).Contexts;
Assert.AreEqual(2, contexts.Length);
Assert.IsTrue(contexts.Any(c => c.Context == window));
}
}
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Get browsing context tree with depth
Provides a tree of all browsing contexts descending from the parent browsing context, including the parent browsing context upto the depth value passed.
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
await context.NavigateAsync("https://www.selenium.dev/selenium/web/iframes.html", new() { Wait = ReadinessState.Complete });
var contexts = (await context.GetTreeAsync(new() { MaxDepth = 0 })).Contexts;
Assert.AreEqual(1, contexts.Length);
Assert.IsNull(contexts[0].Children, "Context should not contain iframes as children since depth is 0");/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.GetTree.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System.Linq;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task GetBrowsingContextTree()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/iframes.html", new() { Wait = ReadinessState.Complete });
var contexts = (await context.GetTreeAsync()).Contexts;
Assert.AreEqual(1, contexts.Length);
Assert.IsNotNull(contexts[0].Children);
Assert.IsTrue(contexts[0].Children.Value.Length >= 1, "Context should contain iframes as children");
}
[TestMethod]
public async Task GetBrowsingContextTreeWithDepth()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/iframes.html", new() { Wait = ReadinessState.Complete });
var contexts = (await context.GetTreeAsync(new() { MaxDepth = 0 })).Contexts;
Assert.AreEqual(1, contexts.Length);
Assert.IsNull(contexts[0].Children, "Context should not contain iframes as children since depth is 0");
}
[TestMethod]
public async Task GetAllTopLevelBrowsingContexts()
{
var window = (await bidi.BrowsingContext.CreateAsync(ContextType.Window)).Context;
var contexts = (await bidi.BrowsingContext.GetTreeAsync()).Contexts;
Assert.AreEqual(2, contexts.Length);
Assert.IsTrue(contexts.Any(c => c.Context == window));
}
}
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Get All Top level browsing contexts
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
var window = (await bidi.BrowsingContext.CreateAsync(ContextType.Window)).Context;
var contexts = (await bidi.BrowsingContext.GetTreeAsync()).Contexts;
Assert.AreEqual(2, contexts.Length);
Assert.IsTrue(contexts.Any(c => c.Context == window));/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.GetTree.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System.Linq;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task GetBrowsingContextTree()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/iframes.html", new() { Wait = ReadinessState.Complete });
var contexts = (await context.GetTreeAsync()).Contexts;
Assert.AreEqual(1, contexts.Length);
Assert.IsNotNull(contexts[0].Children);
Assert.IsTrue(contexts[0].Children.Value.Length >= 1, "Context should contain iframes as children");
}
[TestMethod]
public async Task GetBrowsingContextTreeWithDepth()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/iframes.html", new() { Wait = ReadinessState.Complete });
var contexts = (await context.GetTreeAsync(new() { MaxDepth = 0 })).Contexts;
Assert.AreEqual(1, contexts.Length);
Assert.IsNull(contexts[0].Children, "Context should not contain iframes as children since depth is 0");
}
[TestMethod]
public async Task GetAllTopLevelBrowsingContexts()
{
var window = (await bidi.BrowsingContext.CreateAsync(ContextType.Window)).Context;
var contexts = (await bidi.BrowsingContext.GetTreeAsync()).Contexts;
Assert.AreEqual(2, contexts.Length);
Assert.IsTrue(contexts.Any(c => c.Context == window));
}
}
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Close a tab/window
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
[TestMethod]
public async Task CloseTab()
{
var context = (await bidi.BrowsingContext.CreateAsync(ContextType.Tab)).Context;
await context.CloseAsync();
}
[TestMethod]
public async Task CloseWindow()
{
var context = (await bidi.BrowsingContext.CreateAsync(ContextType.Window)).Context;
await context.CloseAsync();/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Close.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task CloseTab()
{
var context = (await bidi.BrowsingContext.CreateAsync(ContextType.Tab)).Context;
await context.CloseAsync();
}
[TestMethod]
public async Task CloseWindow()
{
var context = (await bidi.BrowsingContext.CreateAsync(ContextType.Window)).Context;
await context.CloseAsync();
}
}
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Activate a browsing context
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
await context.ActivateAsync();/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Activate.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task Activate()
{
await context.ActivateAsync();
}
}
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
await window1.activate()/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Reload a browsing context
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
var info = await context.ReloadAsync();
Assert.IsNotNull(info);
Assert.IsNotNull(info.Navigation);
StringAssert.Contains(info.Url, "/bidi/logEntryAdded.html");/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Reload.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task Reload()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
var info = await context.ReloadAsync();
Assert.IsNotNull(info);
Assert.IsNotNull(info.Navigation);
StringAssert.Contains(info.Url, "/bidi/logEntryAdded.html");
}
}
await browsingContext.reload(undefined, 'complete')/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Handle user prompt
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
// temporary use firefox because of chrome automatically handle prompts
using var driver = new FirefoxDriver(new FirefoxOptions() { UseWebSocketUrl = true, UnhandledPromptBehavior = UnhandledPromptBehavior.Ignore });
var bidi = await driver.AsBiDiAsync();
var context = (await bidi.BrowsingContext.GetTreeAsync()).Contexts[0].Context;
driver.Url = "https://www.selenium.dev/selenium/web/alerts.html";
TaskCompletionSource<UserPromptOpenedEventArgs> promptOpened = new();
await bidi.BrowsingContext.UserPromptOpened.SubscribeAsync(args => promptOpened.TrySetResult(args));
driver.FindElement(By.Id("prompt-with-default")).Click();
await promptOpened.Task.WaitAsync(TimeSpan.FromSeconds(5));
await context.HandleUserPromptAsync(new() { Accept = true, UserText = "Selenium automates browsers" });/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.HandleUserPrompt.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.BiDi;
using OpenQA.Selenium.BiDi.BrowsingContext;
using OpenQA.Selenium.Firefox;
using System;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task HandleUserPrompt()
{
// temporary use firefox because of chrome automatically handle prompts
using var driver = new FirefoxDriver(new FirefoxOptions() { UseWebSocketUrl = true, UnhandledPromptBehavior = UnhandledPromptBehavior.Ignore });
var bidi = await driver.AsBiDiAsync();
var context = (await bidi.BrowsingContext.GetTreeAsync()).Contexts[0].Context;
driver.Url = "https://www.selenium.dev/selenium/web/alerts.html";
TaskCompletionSource<UserPromptOpenedEventArgs> promptOpened = new();
await bidi.BrowsingContext.UserPromptOpened.SubscribeAsync(args => promptOpened.TrySetResult(args));
driver.FindElement(By.Id("prompt-with-default")).Click();
await promptOpened.Task.WaitAsync(TimeSpan.FromSeconds(5));
await context.HandleUserPromptAsync(new() { Accept = true, UserText = "Selenium automates browsers" });
}
}
await browsingContext.handleUserPrompt(true, userText)/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Capture Screenshot
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
var screenshot = await context.CaptureScreenshotAsync();
Assert.IsNotNull(screenshot);
Assert.IsNotNull(screenshot.Data);
Assert.IsNotNull(screenshot.ToByteArray());/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.CaptureScreenshot.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task CaptureScreenshot()
{
var screenshot = await context.CaptureScreenshotAsync();
Assert.IsNotNull(screenshot);
Assert.IsNotNull(screenshot.Data);
Assert.IsNotNull(screenshot.ToByteArray());
}
[TestMethod]
public async Task CaptureViewportScreenshot()
{
var screenshot = await context.CaptureScreenshotAsync(new() { Clip = new BoxClipRectangle(5, 5, 10, 10) });
Assert.IsNotNull(screenshot);
Assert.IsNotNull(screenshot.Data);
}
[TestMethod]
public async Task CaptureElementScreenshot()
{
driver.Url = "https://www.selenium.dev/selenium/web/formPage.html";
var nodes = (await context.LocateNodesAsync(new CssLocator("#checky"))).Nodes;
Assert.IsTrue(nodes.Length > 0, "Expected to locate #checky");
var screenshot = await context.CaptureScreenshotAsync(new() { Clip = new ElementClipRectangle(nodes[0]) });
Assert.IsNotNull(screenshot);
Assert.IsNotNull(screenshot.Data);
}
}
const response = await browsingContext.captureScreenshot()/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Capture Viewport Screenshot
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
var screenshot = await context.CaptureScreenshotAsync(new() { Clip = new BoxClipRectangle(5, 5, 10, 10) });
Assert.IsNotNull(screenshot);
Assert.IsNotNull(screenshot.Data);/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.CaptureScreenshot.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task CaptureScreenshot()
{
var screenshot = await context.CaptureScreenshotAsync();
Assert.IsNotNull(screenshot);
Assert.IsNotNull(screenshot.Data);
Assert.IsNotNull(screenshot.ToByteArray());
}
[TestMethod]
public async Task CaptureViewportScreenshot()
{
var screenshot = await context.CaptureScreenshotAsync(new() { Clip = new BoxClipRectangle(5, 5, 10, 10) });
Assert.IsNotNull(screenshot);
Assert.IsNotNull(screenshot.Data);
}
[TestMethod]
public async Task CaptureElementScreenshot()
{
driver.Url = "https://www.selenium.dev/selenium/web/formPage.html";
var nodes = (await context.LocateNodesAsync(new CssLocator("#checky"))).Nodes;
Assert.IsTrue(nodes.Length > 0, "Expected to locate #checky");
var screenshot = await context.CaptureScreenshotAsync(new() { Clip = new ElementClipRectangle(nodes[0]) });
Assert.IsNotNull(screenshot);
Assert.IsNotNull(screenshot.Data);
}
}
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Capture Element Screenshot
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
driver.Url = "https://www.selenium.dev/selenium/web/formPage.html";
var nodes = (await context.LocateNodesAsync(new CssLocator("#checky"))).Nodes;
Assert.IsTrue(nodes.Length > 0, "Expected to locate #checky");
var screenshot = await context.CaptureScreenshotAsync(new() { Clip = new ElementClipRectangle(nodes[0]) });
Assert.IsNotNull(screenshot);
Assert.IsNotNull(screenshot.Data);/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.CaptureScreenshot.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task CaptureScreenshot()
{
var screenshot = await context.CaptureScreenshotAsync();
Assert.IsNotNull(screenshot);
Assert.IsNotNull(screenshot.Data);
Assert.IsNotNull(screenshot.ToByteArray());
}
[TestMethod]
public async Task CaptureViewportScreenshot()
{
var screenshot = await context.CaptureScreenshotAsync(new() { Clip = new BoxClipRectangle(5, 5, 10, 10) });
Assert.IsNotNull(screenshot);
Assert.IsNotNull(screenshot.Data);
}
[TestMethod]
public async Task CaptureElementScreenshot()
{
driver.Url = "https://www.selenium.dev/selenium/web/formPage.html";
var nodes = (await context.LocateNodesAsync(new CssLocator("#checky"))).Nodes;
Assert.IsTrue(nodes.Length > 0, "Expected to locate #checky");
var screenshot = await context.CaptureScreenshotAsync(new() { Clip = new ElementClipRectangle(nodes[0]) });
Assert.IsNotNull(screenshot);
Assert.IsNotNull(screenshot.Data);
}
}
const response = await browsingContext.captureElementScreenshot(elementId)/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Set Viewport
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
await context.SetViewportAsync(new() { Viewport = new Viewport(Width: 250, Height: 300), DevicePixelRatio = 5 });/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.SetViewport.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task SetViewport()
{
await context.SetViewportAsync(new() { Viewport = new Viewport(Width: 250, Height: 300), DevicePixelRatio = 5 });
}
}
await browsingContext.setViewport(250, 300)/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Print page
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
var pdf = await context.PrintAsync(new() { PageRanges = [1, 2, 3..5, new(3, 5), 7..] });
Assert.IsNotNull(pdf);
Assert.IsNotNull(pdf.Data);
Assert.IsNotNull(pdf.ToByteArray());/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Print.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task PrintPage()
{
var pdf = await context.PrintAsync(new() { PageRanges = [1, 2, 3..5, new(3, 5), 7..] });
Assert.IsNotNull(pdf);
Assert.IsNotNull(pdf.Data);
Assert.IsNotNull(pdf.ToByteArray());
}
}
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Navigate back
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
await context.TraverseHistoryAsync(-1);
var url = await WaitForUrlAsync("about:blank");
Assert.AreEqual("about:blank", url);/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Navigate.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task NavigateToUrl()
{
var info = await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assert.IsNotNull(info);
Assert.IsNotNull(info.Navigation);
StringAssert.Contains(info.Url, "/bidi/logEntryAdded.html");
}
[TestMethod]
public async Task NavigateToUrlWithReadinessState()
{
var info = await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
Assert.IsNotNull(info);
Assert.IsNotNull(info.Navigation);
StringAssert.Contains(info.Url, "/bidi/logEntryAdded.html");
}
[TestMethod]
public async Task NavigateBack()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
await context.TraverseHistoryAsync(-1);
var url = await WaitForUrlAsync("about:blank");
Assert.AreEqual("about:blank", url);
}
[TestMethod]
public async Task NavigateForward()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
await context.TraverseHistoryAsync(-1);
await WaitForUrlAsync("about:blank");
await context.TraverseHistoryAsync(1);
var url = await WaitForUrlAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assert.AreEqual("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", url);
}
private async Task<string> WaitForUrlAsync(string expectedUrl)
{
var deadline = DateTime.UtcNow.AddSeconds(5);
string url;
do
{
url = (await context.GetTreeAsync()).Contexts[0].Url;
if (url == expectedUrl) return url;
await Task.Delay(100);
} while (DateTime.UtcNow < deadline);
return url;
}
[TestMethod]
public async Task TraverseHistory()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
await context.TraverseHistoryAsync(-1);
var url = await WaitForUrlAsync("about:blank");
Assert.AreEqual("about:blank", url);
}
}
await browsingContext.back()/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Navigate forward
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
await context.TraverseHistoryAsync(-1);
await WaitForUrlAsync("about:blank");
await context.TraverseHistoryAsync(1);
var url = await WaitForUrlAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assert.AreEqual("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", url);/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Navigate.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task NavigateToUrl()
{
var info = await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assert.IsNotNull(info);
Assert.IsNotNull(info.Navigation);
StringAssert.Contains(info.Url, "/bidi/logEntryAdded.html");
}
[TestMethod]
public async Task NavigateToUrlWithReadinessState()
{
var info = await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
Assert.IsNotNull(info);
Assert.IsNotNull(info.Navigation);
StringAssert.Contains(info.Url, "/bidi/logEntryAdded.html");
}
[TestMethod]
public async Task NavigateBack()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
await context.TraverseHistoryAsync(-1);
var url = await WaitForUrlAsync("about:blank");
Assert.AreEqual("about:blank", url);
}
[TestMethod]
public async Task NavigateForward()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
await context.TraverseHistoryAsync(-1);
await WaitForUrlAsync("about:blank");
await context.TraverseHistoryAsync(1);
var url = await WaitForUrlAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assert.AreEqual("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", url);
}
private async Task<string> WaitForUrlAsync(string expectedUrl)
{
var deadline = DateTime.UtcNow.AddSeconds(5);
string url;
do
{
url = (await context.GetTreeAsync()).Contexts[0].Url;
if (url == expectedUrl) return url;
await Task.Delay(100);
} while (DateTime.UtcNow < deadline);
return url;
}
[TestMethod]
public async Task TraverseHistory()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
await context.TraverseHistoryAsync(-1);
var url = await WaitForUrlAsync("about:blank");
Assert.AreEqual("about:blank", url);
}
}
await browsingContext.forward()/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Traverse history
/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.BiDiException;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationResult;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.remote.RemoteWebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
class BrowsingContextTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
@Test
void testCreateABrowsingContextForGivenId() {
String id = driver.getWindowHandle();
BrowsingContext browsingContext = new BrowsingContext(driver, id);
Assertions.assertEquals(id, browsingContext.getId());
}
@Test
void testCreateAWindow() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.WINDOW);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testCreateATab() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
Assertions.assertNotNull(browsingContext.getId());
}
@Test
void testNavigateToAUrl() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testNavigateToAUrlWithReadinessState() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
NavigationResult info = browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html",
ReadinessState.COMPLETE);
Assertions.assertNotNull(browsingContext.getId());
Assertions.assertNotNull(info.getNavigationId());
Assertions.assertTrue(info.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testGetTreeWithAChild() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree();
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertEquals(1, info.getChildren().size());
Assertions.assertEquals(referenceContextId, info.getId());
Assertions.assertTrue(info.getChildren().get(0).getUrl().contains("formPage.html"));
}
@Test
void testGetTreeWithDepth() {
String referenceContextId = driver.getWindowHandle();
BrowsingContext parentWindow = new BrowsingContext(driver, referenceContextId);
parentWindow.navigate("https://www.selenium.dev/selenium/web/iframes.html", ReadinessState.COMPLETE);
List<BrowsingContextInfo> contextInfoList = parentWindow.getTree(0);
Assertions.assertEquals(1, contextInfoList.size());
BrowsingContextInfo info = contextInfoList.get(0);
Assertions.assertNull(info.getChildren()); // since depth is 0
Assertions.assertEquals(referenceContextId, info.getId());
}
@Test
void testGetAllTopLevelContexts() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
List<BrowsingContextInfo> contextInfoList = window1.getTopLevelContexts();
Assertions.assertEquals(2, contextInfoList.size());
}
@Test
void testCloseAWindow() {
BrowsingContext window1 = new BrowsingContext(driver, WindowType.WINDOW);
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window2.close();
Assertions.assertThrows(BiDiException.class, window2::getTree);
}
@Test
void testCloseATab() {
BrowsingContext tab1 = new BrowsingContext(driver, WindowType.TAB);
BrowsingContext tab2 = new BrowsingContext(driver, WindowType.TAB);
tab2.close();
Assertions.assertThrows(BiDiException.class, tab2::getTree);
}
@Test
void testActivateABrowsingContext() {
BrowsingContext window1 = new BrowsingContext(driver, driver.getWindowHandle());
BrowsingContext window2 = new BrowsingContext(driver, WindowType.WINDOW);
window1.activate();
boolean isFocused = (boolean) ((JavascriptExecutor) driver).executeScript("return document.hasFocus();");
Assertions.assertTrue(isFocused);
}
@Test
void testReloadABrowsingContext() {
BrowsingContext browsingContext = new BrowsingContext(driver, WindowType.TAB);
browsingContext.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationResult reloadInfo = browsingContext.reload(ReadinessState.INTERACTIVE);
Assertions.assertNotNull(reloadInfo.getNavigationId());
Assertions.assertTrue(reloadInfo.getUrl().contains("/bidi/logEntryAdded.html"));
}
@Test
void testHandleUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt();
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testAcceptUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testDismissUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
browsingContext.handleUserPrompt("true");
Assertions.assertTrue(driver.getPageSource().contains("Testing Alerts and Stuff"));
}
@Test
void testPassUserTextToUserPrompt() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(true, userText);
Assertions.assertTrue(driver.getPageSource().contains(userText));
}
@Test
void testDismissUserPromptWithText() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt-with-default")).click();
String userText = "Selenium automates browsers";
browsingContext.handleUserPrompt(false, userText);
Assertions.assertFalse(driver.getPageSource().contains(userText));
}
@Test
void textCaptureScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
String screenshot = browsingContext.captureScreenshot();
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureViewportScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/coordinates_tests/simple_page.html");
WebElement element = driver.findElement(By.id("box"));
Rectangle elementRectangle = element.getRect();
String screenshot =
browsingContext.captureBoxScreenshot(
elementRectangle.getX(), elementRectangle.getY(), 5, 5);
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textCaptureElementScreenshot() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
WebElement element = driver.findElement(By.id("checky"));
String screenshot = browsingContext.captureElementScreenshot(((RemoteWebElement) element).getId());
Assertions.assertFalse(screenshot.isEmpty());
}
@Test
void textSetViewport() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300);
List<Long> newViewportSize =
(List<Long>)
((JavascriptExecutor) driver)
.executeScript("return [window.innerWidth, window.innerHeight];");
Assertions.assertEquals(250, newViewportSize.get(0));
Assertions.assertEquals(300, newViewportSize.get(1));
}
@Test
void textSetViewportWithDevicePixelRatio() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
browsingContext.setViewport(250, 300, 5);
Long newDevicePixelRatio =
(Long) ((JavascriptExecutor) driver).executeScript("return window.devicePixelRatio");
Assertions.assertEquals(5, newDevicePixelRatio);
}
@Test
void testPrintPage() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
PrintOptions printOptions = new PrintOptions();
String printPage = browsingContext.print(printOptions);
Assertions.assertFalse(printPage.isEmpty());
}
@Test
void testNavigateBackInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
@Test
void canNavigateForwardInTheBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.back();
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
browsingContext.forward();
wait.until(titleIs("We Arrive Here"));
}
@Test
void canTraverseBrowserHistory() {
BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle());
browsingContext.navigate("https://www.selenium.dev/selenium/web/formPage.html", ReadinessState.COMPLETE);
wait.until(visibilityOfElementLocated(By.id("imageButton"))).submit();
wait.until(titleIs("We Arrive Here"));
browsingContext.traverseHistory(-1);
Assertions.assertTrue(driver.getPageSource().contains("We Leave From Here"));
}
}
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
await context.TraverseHistoryAsync(-1);
var url = await WaitForUrlAsync("about:blank");
Assert.AreEqual("about:blank", url);/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Navigate.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task NavigateToUrl()
{
var info = await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assert.IsNotNull(info);
Assert.IsNotNull(info.Navigation);
StringAssert.Contains(info.Url, "/bidi/logEntryAdded.html");
}
[TestMethod]
public async Task NavigateToUrlWithReadinessState()
{
var info = await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
Assert.IsNotNull(info);
Assert.IsNotNull(info.Navigation);
StringAssert.Contains(info.Url, "/bidi/logEntryAdded.html");
}
[TestMethod]
public async Task NavigateBack()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
await context.TraverseHistoryAsync(-1);
var url = await WaitForUrlAsync("about:blank");
Assert.AreEqual("about:blank", url);
}
[TestMethod]
public async Task NavigateForward()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
await context.TraverseHistoryAsync(-1);
await WaitForUrlAsync("about:blank");
await context.TraverseHistoryAsync(1);
var url = await WaitForUrlAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html");
Assert.AreEqual("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", url);
}
private async Task<string> WaitForUrlAsync(string expectedUrl)
{
var deadline = DateTime.UtcNow.AddSeconds(5);
string url;
do
{
url = (await context.GetTreeAsync()).Contexts[0].Url;
if (url == expectedUrl) return url;
await Task.Delay(100);
} while (DateTime.UtcNow < deadline);
return url;
}
[TestMethod]
public async Task TraverseHistory()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
await context.TraverseHistoryAsync(-1);
var url = await WaitForUrlAsync("about:blank");
Assert.AreEqual("about:blank", url);
}
}
await browsingContext.traverseHistory(-1)/examples/javascript/test/bidirectional/browsingContext.spec.js
const {By, until, Builder} = require("selenium-webdriver");
const firefox = require('selenium-webdriver/firefox');
const BrowsingContext = require('selenium-webdriver/bidi/browsingContext');
const assert = require("assert");
describe('Browsing Context', function () {
let driver
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let pngMagicNumber = 'iVBOR'
beforeEach(async function () {
const options = new firefox.Options().enableBidi()
options.setAlertBehavior('ignore')
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build()
})
afterEach(async function () {
await driver.quit()
})
it('test create a browsing context for given id', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
assert.equal(browsingContext.id, id)
})
it('test create a window', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a window with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'window',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
assert.notEqual(browsingContext.id, null)
})
it('test create a tab with a reference context', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
referenceContext: await driver.getWindowHandle(),
})
assert.notEqual(browsingContext.id, null)
})
it('test navigate to a url', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
let info = await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html')
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test navigate to a url with readiness state', async function () {
const browsingContext = await BrowsingContext(driver, {
type: 'tab',
})
const info = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html',
'complete'
)
assert.notEqual(browsingContext.id, null)
assert.notEqual(info.navigationId, null)
assert(info.url.includes('/bidi/logEntryAdded.html'))
})
it('test get tree with a child', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree()
assert.equal(contextInfo.children.length, 1)
assert.equal(contextInfo.id, browsingContextId)
assert(contextInfo.children[0]['url'].includes('formPage.html'))
})
it('test get tree with depth', async function () {
const browsingContextId = await driver.getWindowHandle()
const parentWindow = await BrowsingContext(driver, {
browsingContextId: browsingContextId,
})
await parentWindow.navigate('https://www.selenium.dev/selenium/web/iframes.html', 'complete')
const contextInfo = await parentWindow.getTree(0)
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.id, browsingContextId)
})
it('test close a window', async function () {
const window1 = await BrowsingContext(driver, {type: 'window'})
const window2 = await BrowsingContext(driver, {type: 'window'})
await window2.close()
assert.doesNotThrow(async function () {
await window1.getTree()
})
await assert.rejects(window2.getTree(), {message: 'no such frame'})
})
it('test close a tab', async function () {
const tab1 = await BrowsingContext(driver, {type: 'tab'})
const tab2 = await BrowsingContext(driver, {type: 'tab'})
await tab2.close()
assert.doesNotThrow(async function () {
await tab1.getTree()
})
await assert.rejects(tab2.getTree(), {message: 'no such frame'})
})
it('can print PDF with all valid parameters', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/printPage.html")
const result = await browsingContext.printPage({
orientation: 'landscape',
scale: 1,
background: true,
width: 30,
height: 30,
top: 1,
bottom: 1,
left: 1,
right: 1,
shrinkToFit: true,
pageRanges: ['1-2'],
})
let base64Code = result.data.slice(0, 5)
assert.strictEqual(base64Code, 'JVBER')
})
it('can take box screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureBoxScreenshot(5, 5, 10, 10)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can take element screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/formPage.html")
const element = await driver.findElement(By.id('checky'))
const elementId = await element.getId()
const response = await browsingContext.captureElementScreenshot(elementId)
const base64code = response.slice(0, 5)
assert.equal(base64code, 'iVBOR')
})
it('can activate a browsing context', async function () {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, {
type: 'window',
})
const result = await driver.executeScript('return document.hasFocus();')
assert.equal(result, false)
await window1.activate()
const result2 = await driver.executeScript('return document.hasFocus();')
assert.equal(result2, true)
})
it('can handle user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt()
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can accept user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(true)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can dismiss user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
await browsingContext.handleUserPrompt(false)
const result = await driver.getTitle()
assert.equal(result, 'Testing Alerts')
})
it('can pass user text to user prompt', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(undefined, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can accept user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('prompt')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(true, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), true)
})
it('can dismiss user prompt with user text', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/alerts.html")
await driver.findElement(By.id('alert')).click()
await driver.wait(until.alertIsPresent())
const userText = 'Selenium automates browsers'
await browsingContext.handleUserPrompt(false, userText)
const result = await driver.getPageSource()
assert.equal(result.includes(userText), false)
})
it('can set viewport', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await driver.get("https://www.selenium.dev/selenium/web/blank.html")
await browsingContext.setViewport(250, 300)
const result = await driver.executeScript('return [window.innerWidth, window.innerHeight];')
assert.equal(result[0], 250)
assert.equal(result[1], 300)
})
it('can reload a browsing context', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const result = await browsingContext.navigate(
'https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
await browsingContext.reload(undefined, 'complete')
assert.notEqual(result.navigationId, null)
assert(result.url.includes('/bidi/logEntryAdded.html'))
})
it('can take screenshot', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
const response = await browsingContext.captureScreenshot()
const base64code = response.slice(startIndex, endIndex)
assert.equal(base64code, pngMagicNumber)
})
it('can traverse browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.traverseHistory(-1)
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate back in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
})
it('can navigate forward in browser history', async function () {
const id = await driver.getWindowHandle()
const browsingContext = await BrowsingContext(driver, {
browsingContextId: id,
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/formPage.html', 'complete')
await driver.wait(until.elementLocated(By.id('imageButton'))).submit()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
await browsingContext.back()
const source = await driver.getPageSource()
assert.equal(source.includes('We Leave From Here'), true)
await browsingContext.forward()
await driver.wait(until.titleIs('We Arrive Here'), 2500)
});
it('Get All Top level browsing contexts', async () => {
const id = await driver.getWindowHandle()
const window1 = await BrowsingContext(driver, {
browsingContextId: id,
})
await BrowsingContext(driver, { type: 'window' })
const res = await window1.getTopLevelContexts()
assert.equal(res.length, 2)
})
})
Events
This section contains the APIs related to browsing context events.
Browsing Context Created Event
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextCreated(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.WINDOW).getWindowHandle();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextInspectorTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.module.BrowsingContextInspector;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationInfo;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.bidi.browsingcontext.UserPromptClosed;
import org.openqa.selenium.bidi.browsingcontext.UserPromptOpened;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
class BrowsingContextInspectorTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
}
@Test
void canListenToWindowBrowsingContextCreatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextCreated(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.WINDOW).getWindowHandle();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
}
}
@Test
void canListenToTabBrowsingContextCreatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextCreated(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.TAB).getWindowHandle();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
}
}
@Test
void canListenToDomContentLoadedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onDomContentLoaded(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToBrowsingContextLoadedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextLoaded(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToNavigationStartedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onNavigationStarted(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToFragmentNavigatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/linked_image.html", ReadinessState.COMPLETE);
inspector.onFragmentNavigated(future::complete);
context.navigate("https://www.selenium.dev/selenium/web/linked_image.html#linkToAnchorOnThisPage", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("linkToAnchorOnThisPage"));
}
}
@Test
void canListenToUserPromptOpenedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<UserPromptOpened> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
inspector.onUserPromptOpened(future::complete);
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
UserPromptOpened userPromptOpened = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(context.getId(), userPromptOpened.getBrowsingContextId());
}
}
@Test
void canListenToUserPromptClosedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<UserPromptClosed> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
inspector.onUserPromptClosed(future::complete);
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt")).click();
context.handleUserPrompt(true, "selenium");
UserPromptClosed userPromptClosed = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(context.getId(), userPromptClosed.getBrowsingContextId());
}
}
@Test
void canListenToBrowsingContextDestroyedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextDestroyed(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.WINDOW).getWindowHandle();
driver.close();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
Assertions.assertTrue(browsingContextInfo.getUrl().contains("about:blank"));
}
}
}
TaskCompletionSource<ContextCreatedEventArgs> tcs = new();
await bidi.BrowsingContext.ContextCreated.SubscribeAsync(args => tcs.TrySetResult(args));
driver.SwitchTo().NewWindow(OpenQA.Selenium.WindowType.Window);
var info = await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.IsNotNull(info);
Console.WriteLine(info);/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Event.BrowsingContextCreated.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task BrowsingContextCreatedEvent()
{
TaskCompletionSource<ContextCreatedEventArgs> tcs = new();
await bidi.BrowsingContext.ContextCreated.SubscribeAsync(args => tcs.TrySetResult(args));
driver.SwitchTo().NewWindow(OpenQA.Selenium.WindowType.Window);
var info = await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.IsNotNull(info);
Console.WriteLine(info);
}
}
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextCreated((entry) => {
contextInfo = entry
})
await driver.switchTo().newWindow('window')/examples/javascript/test/bidirectional/browsingContextInspector.spec.js
const BrowsingContextInspector = require("selenium-webdriver/bidi/browsingContextInspector");
const BrowsingContext = require("selenium-webdriver/bidi/browsingContext");
const assert = require("assert");
const firefox = require('selenium-webdriver/firefox');
const {Builder} = require("selenium-webdriver");
describe('Browsing Context Inspector', function () {
let driver
beforeEach(async function () {
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(new firefox.Options().enableBidi())
.build()
})
afterEach(async function () {
await driver.quit()
})
it('can listen to window browsing context created event', async function () {
let contextInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextCreated((entry) => {
contextInfo = entry
})
await driver.switchTo().newWindow('window')
const windowHandle = await driver.getWindowHandle()
assert.equal(contextInfo.id, windowHandle)
assert.equal(contextInfo.url, 'about:blank')
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.parentBrowsingContext, null)
})
it('can listen to tab browsing context created event', async function () {
let contextInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextCreated((entry) => {
contextInfo = entry
})
await driver.switchTo().newWindow('tab')
const tabHandle = await driver.getWindowHandle()
assert.equal(contextInfo.id, tabHandle)
assert.equal(contextInfo.url, 'about:blank')
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.parentBrowsingContext, null)
})
it('can listen to dom content loaded event', async function () {
const browsingContextInspector = await BrowsingContextInspector(driver)
let navigationInfo = null
await browsingContextInspector.onDomContentLoaded((entry) => {
navigationInfo = entry
})
const browsingContext = await BrowsingContext(driver, {
browsingContextId: await driver.getWindowHandle(),
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
assert.equal(navigationInfo.browsingContextId, browsingContext.id)
assert.strictEqual(navigationInfo.url.includes('/bidi/logEntryAdded.html'), true)
})
it('can listen to browsing context loaded event', async function () {
let navigationInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextLoaded((entry) => {
navigationInfo = entry
})
const browsingContext = await BrowsingContext(driver, {
browsingContextId: await driver.getWindowHandle(),
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
assert.equal(navigationInfo.browsingContextId, browsingContext.id)
assert.strictEqual(navigationInfo.url.includes('/bidi/logEntryAdded.html'), true)
})
it('can listen to fragment navigated event', async function () {
let navigationInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
const browsingContext = await BrowsingContext(driver, {
browsingContextId: await driver.getWindowHandle(),
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/linked_image.html', 'complete')
await browsingContextInspector.onFragmentNavigated((entry) => {
navigationInfo = entry
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/linked_image.html#linkToAnchorOnThisPage', 'complete')
assert.equal(navigationInfo.browsingContextId, browsingContext.id)
assert.strictEqual(navigationInfo.url.includes('linkToAnchorOnThisPage'), true)
})
it('can listen to browsing context destroyed event', async function () {
let contextInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextDestroyed((entry) => {
contextInfo = entry
})
await driver.switchTo().newWindow('window')
const windowHandle = await driver.getWindowHandle()
await driver.close()
assert.equal(contextInfo.id, windowHandle)
assert.equal(contextInfo.url, 'about:blank')
assert.equal(contextInfo.children.length, 0)
assert.equal(contextInfo.parentBrowsingContext, null)
})
})
Dom Content loaded Event
String windowHandle = driver.switchTo().newWindow(WindowType.TAB).getWindowHandle();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
}
}
@Test
void canListenToDomContentLoadedEvent()/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextInspectorTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.module.BrowsingContextInspector;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationInfo;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.bidi.browsingcontext.UserPromptClosed;
import org.openqa.selenium.bidi.browsingcontext.UserPromptOpened;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
class BrowsingContextInspectorTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
}
@Test
void canListenToWindowBrowsingContextCreatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextCreated(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.WINDOW).getWindowHandle();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
}
}
@Test
void canListenToTabBrowsingContextCreatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextCreated(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.TAB).getWindowHandle();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
}
}
@Test
void canListenToDomContentLoadedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onDomContentLoaded(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToBrowsingContextLoadedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextLoaded(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToNavigationStartedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onNavigationStarted(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToFragmentNavigatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/linked_image.html", ReadinessState.COMPLETE);
inspector.onFragmentNavigated(future::complete);
context.navigate("https://www.selenium.dev/selenium/web/linked_image.html#linkToAnchorOnThisPage", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("linkToAnchorOnThisPage"));
}
}
@Test
void canListenToUserPromptOpenedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<UserPromptOpened> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
inspector.onUserPromptOpened(future::complete);
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
UserPromptOpened userPromptOpened = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(context.getId(), userPromptOpened.getBrowsingContextId());
}
}
@Test
void canListenToUserPromptClosedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<UserPromptClosed> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
inspector.onUserPromptClosed(future::complete);
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt")).click();
context.handleUserPrompt(true, "selenium");
UserPromptClosed userPromptClosed = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(context.getId(), userPromptClosed.getBrowsingContextId());
}
}
@Test
void canListenToBrowsingContextDestroyedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextDestroyed(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.WINDOW).getWindowHandle();
driver.close();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
Assertions.assertTrue(browsingContextInfo.getUrl().contains("about:blank"));
}
}
}
TaskCompletionSource<DomContentLoadedEventArgs> tcs = new();
await context.DomContentLoaded.SubscribeAsync(args => tcs.TrySetResult(args));
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
var navigationInfo = await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.IsNotNull(navigationInfo);
Console.WriteLine(navigationInfo);/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Event.DomContentLoaded.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task DomContentLoadedEvent()
{
TaskCompletionSource<DomContentLoadedEventArgs> tcs = new();
await context.DomContentLoaded.SubscribeAsync(args => tcs.TrySetResult(args));
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
var navigationInfo = await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.IsNotNull(navigationInfo);
Console.WriteLine(navigationInfo);
}
}
const browsingContextInspector = await BrowsingContextInspector(driver)
let navigationInfo = null
await browsingContextInspector.onDomContentLoaded((entry) => {
navigationInfo = entry
})
const browsingContext = await BrowsingContext(driver, {
browsingContextId: await driver.getWindowHandle(),
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')/examples/javascript/test/bidirectional/browsingContextInspector.spec.js
const BrowsingContextInspector = require("selenium-webdriver/bidi/browsingContextInspector");
const BrowsingContext = require("selenium-webdriver/bidi/browsingContext");
const assert = require("assert");
const firefox = require('selenium-webdriver/firefox');
const {Builder} = require("selenium-webdriver");
describe('Browsing Context Inspector', function () {
let driver
beforeEach(async function () {
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(new firefox.Options().enableBidi())
.build()
})
afterEach(async function () {
await driver.quit()
})
it('can listen to window browsing context created event', async function () {
let contextInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextCreated((entry) => {
contextInfo = entry
})
await driver.switchTo().newWindow('window')
const windowHandle = await driver.getWindowHandle()
assert.equal(contextInfo.id, windowHandle)
assert.equal(contextInfo.url, 'about:blank')
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.parentBrowsingContext, null)
})
it('can listen to tab browsing context created event', async function () {
let contextInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextCreated((entry) => {
contextInfo = entry
})
await driver.switchTo().newWindow('tab')
const tabHandle = await driver.getWindowHandle()
assert.equal(contextInfo.id, tabHandle)
assert.equal(contextInfo.url, 'about:blank')
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.parentBrowsingContext, null)
})
it('can listen to dom content loaded event', async function () {
const browsingContextInspector = await BrowsingContextInspector(driver)
let navigationInfo = null
await browsingContextInspector.onDomContentLoaded((entry) => {
navigationInfo = entry
})
const browsingContext = await BrowsingContext(driver, {
browsingContextId: await driver.getWindowHandle(),
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
assert.equal(navigationInfo.browsingContextId, browsingContext.id)
assert.strictEqual(navigationInfo.url.includes('/bidi/logEntryAdded.html'), true)
})
it('can listen to browsing context loaded event', async function () {
let navigationInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextLoaded((entry) => {
navigationInfo = entry
})
const browsingContext = await BrowsingContext(driver, {
browsingContextId: await driver.getWindowHandle(),
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
assert.equal(navigationInfo.browsingContextId, browsingContext.id)
assert.strictEqual(navigationInfo.url.includes('/bidi/logEntryAdded.html'), true)
})
it('can listen to fragment navigated event', async function () {
let navigationInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
const browsingContext = await BrowsingContext(driver, {
browsingContextId: await driver.getWindowHandle(),
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/linked_image.html', 'complete')
await browsingContextInspector.onFragmentNavigated((entry) => {
navigationInfo = entry
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/linked_image.html#linkToAnchorOnThisPage', 'complete')
assert.equal(navigationInfo.browsingContextId, browsingContext.id)
assert.strictEqual(navigationInfo.url.includes('linkToAnchorOnThisPage'), true)
})
it('can listen to browsing context destroyed event', async function () {
let contextInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextDestroyed((entry) => {
contextInfo = entry
})
await driver.switchTo().newWindow('window')
const windowHandle = await driver.getWindowHandle()
await driver.close()
assert.equal(contextInfo.id, windowHandle)
assert.equal(contextInfo.url, 'about:blank')
assert.equal(contextInfo.children.length, 0)
assert.equal(contextInfo.parentBrowsingContext, null)
})
})
Browsing Context Loaded Event
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextLoaded(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextInspectorTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.module.BrowsingContextInspector;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationInfo;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.bidi.browsingcontext.UserPromptClosed;
import org.openqa.selenium.bidi.browsingcontext.UserPromptOpened;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
class BrowsingContextInspectorTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
}
@Test
void canListenToWindowBrowsingContextCreatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextCreated(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.WINDOW).getWindowHandle();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
}
}
@Test
void canListenToTabBrowsingContextCreatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextCreated(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.TAB).getWindowHandle();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
}
}
@Test
void canListenToDomContentLoadedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onDomContentLoaded(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToBrowsingContextLoadedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextLoaded(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToNavigationStartedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onNavigationStarted(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToFragmentNavigatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/linked_image.html", ReadinessState.COMPLETE);
inspector.onFragmentNavigated(future::complete);
context.navigate("https://www.selenium.dev/selenium/web/linked_image.html#linkToAnchorOnThisPage", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("linkToAnchorOnThisPage"));
}
}
@Test
void canListenToUserPromptOpenedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<UserPromptOpened> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
inspector.onUserPromptOpened(future::complete);
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
UserPromptOpened userPromptOpened = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(context.getId(), userPromptOpened.getBrowsingContextId());
}
}
@Test
void canListenToUserPromptClosedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<UserPromptClosed> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
inspector.onUserPromptClosed(future::complete);
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt")).click();
context.handleUserPrompt(true, "selenium");
UserPromptClosed userPromptClosed = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(context.getId(), userPromptClosed.getBrowsingContextId());
}
}
@Test
void canListenToBrowsingContextDestroyedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextDestroyed(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.WINDOW).getWindowHandle();
driver.close();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
Assertions.assertTrue(browsingContextInfo.getUrl().contains("about:blank"));
}
}
}
TaskCompletionSource<LoadEventArgs> tcs = new();
await context.Load.SubscribeAsync(args => tcs.TrySetResult(args));
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
var navigationInfo = await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.IsNotNull(navigationInfo);
Console.WriteLine(navigationInfo);/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Event.BrowsingContextLoaded.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task BrowsingContextLoadedEvent()
{
TaskCompletionSource<LoadEventArgs> tcs = new();
await context.Load.SubscribeAsync(args => tcs.TrySetResult(args));
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
var navigationInfo = await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.IsNotNull(navigationInfo);
Console.WriteLine(navigationInfo);
}
}
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextLoaded((entry) => {
navigationInfo = entry
})
const browsingContext = await BrowsingContext(driver, {
browsingContextId: await driver.getWindowHandle(),
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')/examples/javascript/test/bidirectional/browsingContextInspector.spec.js
const BrowsingContextInspector = require("selenium-webdriver/bidi/browsingContextInspector");
const BrowsingContext = require("selenium-webdriver/bidi/browsingContext");
const assert = require("assert");
const firefox = require('selenium-webdriver/firefox');
const {Builder} = require("selenium-webdriver");
describe('Browsing Context Inspector', function () {
let driver
beforeEach(async function () {
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(new firefox.Options().enableBidi())
.build()
})
afterEach(async function () {
await driver.quit()
})
it('can listen to window browsing context created event', async function () {
let contextInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextCreated((entry) => {
contextInfo = entry
})
await driver.switchTo().newWindow('window')
const windowHandle = await driver.getWindowHandle()
assert.equal(contextInfo.id, windowHandle)
assert.equal(contextInfo.url, 'about:blank')
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.parentBrowsingContext, null)
})
it('can listen to tab browsing context created event', async function () {
let contextInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextCreated((entry) => {
contextInfo = entry
})
await driver.switchTo().newWindow('tab')
const tabHandle = await driver.getWindowHandle()
assert.equal(contextInfo.id, tabHandle)
assert.equal(contextInfo.url, 'about:blank')
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.parentBrowsingContext, null)
})
it('can listen to dom content loaded event', async function () {
const browsingContextInspector = await BrowsingContextInspector(driver)
let navigationInfo = null
await browsingContextInspector.onDomContentLoaded((entry) => {
navigationInfo = entry
})
const browsingContext = await BrowsingContext(driver, {
browsingContextId: await driver.getWindowHandle(),
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
assert.equal(navigationInfo.browsingContextId, browsingContext.id)
assert.strictEqual(navigationInfo.url.includes('/bidi/logEntryAdded.html'), true)
})
it('can listen to browsing context loaded event', async function () {
let navigationInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextLoaded((entry) => {
navigationInfo = entry
})
const browsingContext = await BrowsingContext(driver, {
browsingContextId: await driver.getWindowHandle(),
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
assert.equal(navigationInfo.browsingContextId, browsingContext.id)
assert.strictEqual(navigationInfo.url.includes('/bidi/logEntryAdded.html'), true)
})
it('can listen to fragment navigated event', async function () {
let navigationInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
const browsingContext = await BrowsingContext(driver, {
browsingContextId: await driver.getWindowHandle(),
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/linked_image.html', 'complete')
await browsingContextInspector.onFragmentNavigated((entry) => {
navigationInfo = entry
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/linked_image.html#linkToAnchorOnThisPage', 'complete')
assert.equal(navigationInfo.browsingContextId, browsingContext.id)
assert.strictEqual(navigationInfo.url.includes('linkToAnchorOnThisPage'), true)
})
it('can listen to browsing context destroyed event', async function () {
let contextInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextDestroyed((entry) => {
contextInfo = entry
})
await driver.switchTo().newWindow('window')
const windowHandle = await driver.getWindowHandle()
await driver.close()
assert.equal(contextInfo.id, windowHandle)
assert.equal(contextInfo.url, 'about:blank')
assert.equal(contextInfo.children.length, 0)
assert.equal(contextInfo.parentBrowsingContext, null)
})
})
Navigated Started Event
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onNavigationStarted(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextInspectorTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.module.BrowsingContextInspector;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationInfo;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.bidi.browsingcontext.UserPromptClosed;
import org.openqa.selenium.bidi.browsingcontext.UserPromptOpened;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
class BrowsingContextInspectorTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
}
@Test
void canListenToWindowBrowsingContextCreatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextCreated(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.WINDOW).getWindowHandle();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
}
}
@Test
void canListenToTabBrowsingContextCreatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextCreated(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.TAB).getWindowHandle();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
}
}
@Test
void canListenToDomContentLoadedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onDomContentLoaded(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToBrowsingContextLoadedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextLoaded(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToNavigationStartedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onNavigationStarted(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToFragmentNavigatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/linked_image.html", ReadinessState.COMPLETE);
inspector.onFragmentNavigated(future::complete);
context.navigate("https://www.selenium.dev/selenium/web/linked_image.html#linkToAnchorOnThisPage", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("linkToAnchorOnThisPage"));
}
}
@Test
void canListenToUserPromptOpenedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<UserPromptOpened> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
inspector.onUserPromptOpened(future::complete);
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
UserPromptOpened userPromptOpened = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(context.getId(), userPromptOpened.getBrowsingContextId());
}
}
@Test
void canListenToUserPromptClosedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<UserPromptClosed> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
inspector.onUserPromptClosed(future::complete);
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt")).click();
context.handleUserPrompt(true, "selenium");
UserPromptClosed userPromptClosed = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(context.getId(), userPromptClosed.getBrowsingContextId());
}
}
@Test
void canListenToBrowsingContextDestroyedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextDestroyed(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.WINDOW).getWindowHandle();
driver.close();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
Assertions.assertTrue(browsingContextInfo.getUrl().contains("about:blank"));
}
}
}
TaskCompletionSource<NavigationStartedEventArgs> tcs = new();
await context.NavigationStarted.SubscribeAsync(args => tcs.TrySetResult(args));
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
var info = await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.IsNotNull(info);/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Event.NavigationStarted.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task NavigationStartedEvent()
{
TaskCompletionSource<NavigationStartedEventArgs> tcs = new();
await context.NavigationStarted.SubscribeAsync(args => tcs.TrySetResult(args));
await context.NavigateAsync("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", new() { Wait = ReadinessState.Complete });
var info = await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.IsNotNull(info);
}
}
Fragment Navigated Event
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/linked_image.html", ReadinessState.COMPLETE);
inspector.onFragmentNavigated(future::complete);
context.navigate("https://www.selenium.dev/selenium/web/linked_image.html#linkToAnchorOnThisPage", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextInspectorTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.module.BrowsingContextInspector;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationInfo;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.bidi.browsingcontext.UserPromptClosed;
import org.openqa.selenium.bidi.browsingcontext.UserPromptOpened;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
class BrowsingContextInspectorTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
}
@Test
void canListenToWindowBrowsingContextCreatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextCreated(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.WINDOW).getWindowHandle();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
}
}
@Test
void canListenToTabBrowsingContextCreatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextCreated(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.TAB).getWindowHandle();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
}
}
@Test
void canListenToDomContentLoadedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onDomContentLoaded(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToBrowsingContextLoadedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextLoaded(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToNavigationStartedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onNavigationStarted(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToFragmentNavigatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/linked_image.html", ReadinessState.COMPLETE);
inspector.onFragmentNavigated(future::complete);
context.navigate("https://www.selenium.dev/selenium/web/linked_image.html#linkToAnchorOnThisPage", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("linkToAnchorOnThisPage"));
}
}
@Test
void canListenToUserPromptOpenedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<UserPromptOpened> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
inspector.onUserPromptOpened(future::complete);
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
UserPromptOpened userPromptOpened = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(context.getId(), userPromptOpened.getBrowsingContextId());
}
}
@Test
void canListenToUserPromptClosedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<UserPromptClosed> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
inspector.onUserPromptClosed(future::complete);
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt")).click();
context.handleUserPrompt(true, "selenium");
UserPromptClosed userPromptClosed = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(context.getId(), userPromptClosed.getBrowsingContextId());
}
}
@Test
void canListenToBrowsingContextDestroyedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextDestroyed(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.WINDOW).getWindowHandle();
driver.close();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
Assertions.assertTrue(browsingContextInfo.getUrl().contains("about:blank"));
}
}
}
await context.NavigateAsync("https://www.selenium.dev/selenium/web/linked_image.html", new() { Wait = ReadinessState.Complete });
TaskCompletionSource<FragmentNavigatedEventArgs> tcs = new();
await context.FragmentNavigated.SubscribeAsync(args => tcs.TrySetResult(args));
await context.NavigateAsync("https://www.selenium.dev/selenium/web/linked_image.html#linkToAnchorOnThisPage", new() { Wait = ReadinessState.Complete });
var navigationInfo = await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.IsNotNull(navigationInfo);
Console.WriteLine(navigationInfo);/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Event.FragmentNavigated.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task FragmentNavigatedEvent()
{
await context.NavigateAsync("https://www.selenium.dev/selenium/web/linked_image.html", new() { Wait = ReadinessState.Complete });
TaskCompletionSource<FragmentNavigatedEventArgs> tcs = new();
await context.FragmentNavigated.SubscribeAsync(args => tcs.TrySetResult(args));
await context.NavigateAsync("https://www.selenium.dev/selenium/web/linked_image.html#linkToAnchorOnThisPage", new() { Wait = ReadinessState.Complete });
var navigationInfo = await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.IsNotNull(navigationInfo);
Console.WriteLine(navigationInfo);
}
}
const browsingContextInspector = await BrowsingContextInspector(driver)
const browsingContext = await BrowsingContext(driver, {
browsingContextId: await driver.getWindowHandle(),
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/linked_image.html', 'complete')
await browsingContextInspector.onFragmentNavigated((entry) => {
navigationInfo = entry
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/linked_image.html#linkToAnchorOnThisPage', 'complete')/examples/javascript/test/bidirectional/browsingContextInspector.spec.js
const BrowsingContextInspector = require("selenium-webdriver/bidi/browsingContextInspector");
const BrowsingContext = require("selenium-webdriver/bidi/browsingContext");
const assert = require("assert");
const firefox = require('selenium-webdriver/firefox');
const {Builder} = require("selenium-webdriver");
describe('Browsing Context Inspector', function () {
let driver
beforeEach(async function () {
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(new firefox.Options().enableBidi())
.build()
})
afterEach(async function () {
await driver.quit()
})
it('can listen to window browsing context created event', async function () {
let contextInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextCreated((entry) => {
contextInfo = entry
})
await driver.switchTo().newWindow('window')
const windowHandle = await driver.getWindowHandle()
assert.equal(contextInfo.id, windowHandle)
assert.equal(contextInfo.url, 'about:blank')
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.parentBrowsingContext, null)
})
it('can listen to tab browsing context created event', async function () {
let contextInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextCreated((entry) => {
contextInfo = entry
})
await driver.switchTo().newWindow('tab')
const tabHandle = await driver.getWindowHandle()
assert.equal(contextInfo.id, tabHandle)
assert.equal(contextInfo.url, 'about:blank')
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.parentBrowsingContext, null)
})
it('can listen to dom content loaded event', async function () {
const browsingContextInspector = await BrowsingContextInspector(driver)
let navigationInfo = null
await browsingContextInspector.onDomContentLoaded((entry) => {
navigationInfo = entry
})
const browsingContext = await BrowsingContext(driver, {
browsingContextId: await driver.getWindowHandle(),
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
assert.equal(navigationInfo.browsingContextId, browsingContext.id)
assert.strictEqual(navigationInfo.url.includes('/bidi/logEntryAdded.html'), true)
})
it('can listen to browsing context loaded event', async function () {
let navigationInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextLoaded((entry) => {
navigationInfo = entry
})
const browsingContext = await BrowsingContext(driver, {
browsingContextId: await driver.getWindowHandle(),
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
assert.equal(navigationInfo.browsingContextId, browsingContext.id)
assert.strictEqual(navigationInfo.url.includes('/bidi/logEntryAdded.html'), true)
})
it('can listen to fragment navigated event', async function () {
let navigationInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
const browsingContext = await BrowsingContext(driver, {
browsingContextId: await driver.getWindowHandle(),
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/linked_image.html', 'complete')
await browsingContextInspector.onFragmentNavigated((entry) => {
navigationInfo = entry
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/linked_image.html#linkToAnchorOnThisPage', 'complete')
assert.equal(navigationInfo.browsingContextId, browsingContext.id)
assert.strictEqual(navigationInfo.url.includes('linkToAnchorOnThisPage'), true)
})
it('can listen to browsing context destroyed event', async function () {
let contextInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextDestroyed((entry) => {
contextInfo = entry
})
await driver.switchTo().newWindow('window')
const windowHandle = await driver.getWindowHandle()
await driver.close()
assert.equal(contextInfo.id, windowHandle)
assert.equal(contextInfo.url, 'about:blank')
assert.equal(contextInfo.children.length, 0)
assert.equal(contextInfo.parentBrowsingContext, null)
})
})
User Prompt Opened Event
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/linked_image.html", ReadinessState.COMPLETE);
inspector.onFragmentNavigated(future::complete);
context.navigate("https://www.selenium.dev/selenium/web/linked_image.html#linkToAnchorOnThisPage", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextInspectorTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.module.BrowsingContextInspector;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationInfo;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.bidi.browsingcontext.UserPromptClosed;
import org.openqa.selenium.bidi.browsingcontext.UserPromptOpened;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
class BrowsingContextInspectorTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
}
@Test
void canListenToWindowBrowsingContextCreatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextCreated(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.WINDOW).getWindowHandle();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
}
}
@Test
void canListenToTabBrowsingContextCreatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextCreated(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.TAB).getWindowHandle();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
}
}
@Test
void canListenToDomContentLoadedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onDomContentLoaded(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToBrowsingContextLoadedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextLoaded(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToNavigationStartedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onNavigationStarted(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToFragmentNavigatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/linked_image.html", ReadinessState.COMPLETE);
inspector.onFragmentNavigated(future::complete);
context.navigate("https://www.selenium.dev/selenium/web/linked_image.html#linkToAnchorOnThisPage", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("linkToAnchorOnThisPage"));
}
}
@Test
void canListenToUserPromptOpenedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<UserPromptOpened> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
inspector.onUserPromptOpened(future::complete);
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
UserPromptOpened userPromptOpened = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(context.getId(), userPromptOpened.getBrowsingContextId());
}
}
@Test
void canListenToUserPromptClosedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<UserPromptClosed> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
inspector.onUserPromptClosed(future::complete);
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt")).click();
context.handleUserPrompt(true, "selenium");
UserPromptClosed userPromptClosed = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(context.getId(), userPromptClosed.getBrowsingContextId());
}
}
@Test
void canListenToBrowsingContextDestroyedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextDestroyed(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.WINDOW).getWindowHandle();
driver.close();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
Assertions.assertTrue(browsingContextInfo.getUrl().contains("about:blank"));
}
}
}
TaskCompletionSource<UserPromptOpenedEventArgs> tcs = new();
await context.NavigateAsync("https://www.selenium.dev/selenium/web/alerts.html", new() { Wait = ReadinessState.Complete });
// TODO: this event can be a part of context
await bidi.BrowsingContext.UserPromptOpened.SubscribeAsync(args => tcs.TrySetResult(args));
driver.FindElement(By.Id("prompt")).Click();
var userPromptOpenedEventArgs = await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.IsNotNull(userPromptOpenedEventArgs);
Console.WriteLine(userPromptOpenedEventArgs);/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Event.UserPrompt.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.BiDi;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task UserPromptOpenedEvent()
{
TaskCompletionSource<UserPromptOpenedEventArgs> tcs = new();
await context.NavigateAsync("https://www.selenium.dev/selenium/web/alerts.html", new() { Wait = ReadinessState.Complete });
// TODO: this event can be a part of context
await bidi.BrowsingContext.UserPromptOpened.SubscribeAsync(args => tcs.TrySetResult(args));
driver.FindElement(By.Id("prompt")).Click();
var userPromptOpenedEventArgs = await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.IsNotNull(userPromptOpenedEventArgs);
Console.WriteLine(userPromptOpenedEventArgs);
}
[TestMethod]
public async Task UserPromptClosedEvent()
{
TaskCompletionSource<UserPromptOpenedEventArgs> opened = new();
TaskCompletionSource<UserPromptClosedEventArgs> closed = new();
await context.NavigateAsync("https://www.selenium.dev/selenium/web/alerts.html", new() { Wait = ReadinessState.Complete });
// TODO: these events can be a part of context
await bidi.BrowsingContext.UserPromptOpened.SubscribeAsync(args => opened.TrySetResult(args));
await bidi.BrowsingContext.UserPromptClosed.SubscribeAsync(args => closed.TrySetResult(args));
driver.FindElement(By.Id("prompt")).Click();
await opened.Task.WaitAsync(TimeSpan.FromSeconds(5));
try
{
// Chrome's default unhandled prompt behavior may already have closed the
// prompt by this point; tolerate that instead of treating it as a failure.
await context.HandleUserPromptAsync(new() { Accept = true });
}
catch (BiDiException ex) when (ex.Message.Contains("no such alert"))
{
}
var userPromptClosedEventArgs = await closed.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.IsNotNull(userPromptClosedEventArgs);
Console.WriteLine(userPromptClosedEventArgs);
}
}
User Prompt Closed Event
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<UserPromptClosed> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
inspector.onUserPromptClosed(future::complete);
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt")).click();
context.handleUserPrompt(true, "selenium");
UserPromptClosed userPromptClosed = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(context.getId(), userPromptClosed.getBrowsingContextId());/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextInspectorTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.module.BrowsingContextInspector;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationInfo;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.bidi.browsingcontext.UserPromptClosed;
import org.openqa.selenium.bidi.browsingcontext.UserPromptOpened;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
class BrowsingContextInspectorTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
}
@Test
void canListenToWindowBrowsingContextCreatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextCreated(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.WINDOW).getWindowHandle();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
}
}
@Test
void canListenToTabBrowsingContextCreatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextCreated(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.TAB).getWindowHandle();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
}
}
@Test
void canListenToDomContentLoadedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onDomContentLoaded(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToBrowsingContextLoadedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextLoaded(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToNavigationStartedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onNavigationStarted(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToFragmentNavigatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/linked_image.html", ReadinessState.COMPLETE);
inspector.onFragmentNavigated(future::complete);
context.navigate("https://www.selenium.dev/selenium/web/linked_image.html#linkToAnchorOnThisPage", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("linkToAnchorOnThisPage"));
}
}
@Test
void canListenToUserPromptOpenedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<UserPromptOpened> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
inspector.onUserPromptOpened(future::complete);
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
UserPromptOpened userPromptOpened = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(context.getId(), userPromptOpened.getBrowsingContextId());
}
}
@Test
void canListenToUserPromptClosedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<UserPromptClosed> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
inspector.onUserPromptClosed(future::complete);
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt")).click();
context.handleUserPrompt(true, "selenium");
UserPromptClosed userPromptClosed = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(context.getId(), userPromptClosed.getBrowsingContextId());
}
}
@Test
void canListenToBrowsingContextDestroyedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextDestroyed(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.WINDOW).getWindowHandle();
driver.close();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
Assertions.assertTrue(browsingContextInfo.getUrl().contains("about:blank"));
}
}
}
TaskCompletionSource<UserPromptOpenedEventArgs> opened = new();
TaskCompletionSource<UserPromptClosedEventArgs> closed = new();
await context.NavigateAsync("https://www.selenium.dev/selenium/web/alerts.html", new() { Wait = ReadinessState.Complete });
// TODO: these events can be a part of context
await bidi.BrowsingContext.UserPromptOpened.SubscribeAsync(args => opened.TrySetResult(args));
await bidi.BrowsingContext.UserPromptClosed.SubscribeAsync(args => closed.TrySetResult(args));
driver.FindElement(By.Id("prompt")).Click();
await opened.Task.WaitAsync(TimeSpan.FromSeconds(5));
try
{
// Chrome's default unhandled prompt behavior may already have closed the
// prompt by this point; tolerate that instead of treating it as a failure.
await context.HandleUserPromptAsync(new() { Accept = true });
}
catch (BiDiException ex) when (ex.Message.Contains("no such alert"))
{
}
var userPromptClosedEventArgs = await closed.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.IsNotNull(userPromptClosedEventArgs);
Console.WriteLine(userPromptClosedEventArgs);/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Event.UserPrompt.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.BiDi;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task UserPromptOpenedEvent()
{
TaskCompletionSource<UserPromptOpenedEventArgs> tcs = new();
await context.NavigateAsync("https://www.selenium.dev/selenium/web/alerts.html", new() { Wait = ReadinessState.Complete });
// TODO: this event can be a part of context
await bidi.BrowsingContext.UserPromptOpened.SubscribeAsync(args => tcs.TrySetResult(args));
driver.FindElement(By.Id("prompt")).Click();
var userPromptOpenedEventArgs = await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.IsNotNull(userPromptOpenedEventArgs);
Console.WriteLine(userPromptOpenedEventArgs);
}
[TestMethod]
public async Task UserPromptClosedEvent()
{
TaskCompletionSource<UserPromptOpenedEventArgs> opened = new();
TaskCompletionSource<UserPromptClosedEventArgs> closed = new();
await context.NavigateAsync("https://www.selenium.dev/selenium/web/alerts.html", new() { Wait = ReadinessState.Complete });
// TODO: these events can be a part of context
await bidi.BrowsingContext.UserPromptOpened.SubscribeAsync(args => opened.TrySetResult(args));
await bidi.BrowsingContext.UserPromptClosed.SubscribeAsync(args => closed.TrySetResult(args));
driver.FindElement(By.Id("prompt")).Click();
await opened.Task.WaitAsync(TimeSpan.FromSeconds(5));
try
{
// Chrome's default unhandled prompt behavior may already have closed the
// prompt by this point; tolerate that instead of treating it as a failure.
await context.HandleUserPromptAsync(new() { Accept = true });
}
catch (BiDiException ex) when (ex.Message.Contains("no such alert"))
{
}
var userPromptClosedEventArgs = await closed.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.IsNotNull(userPromptClosedEventArgs);
Console.WriteLine(userPromptClosedEventArgs);
}
}
Browsing Context Destroyed Event
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextDestroyed(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.WINDOW).getWindowHandle();
driver.close();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());/examples/java/src/test/java/dev/selenium/bidirectional/webdriver_bidi/BrowsingContextInspectorTest.java
package dev.selenium.bidirectional.webdriver_bidi;
import dev.selenium.BaseTest;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.UnexpectedAlertBehaviour;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.bidi.module.BrowsingContextInspector;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContextInfo;
import org.openqa.selenium.bidi.browsingcontext.NavigationInfo;
import org.openqa.selenium.bidi.browsingcontext.ReadinessState;
import org.openqa.selenium.bidi.browsingcontext.UserPromptClosed;
import org.openqa.selenium.bidi.browsingcontext.UserPromptOpened;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
class BrowsingContextInspectorTest extends BaseTest {
@BeforeEach
public void setup() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability("webSocketUrl", true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.IGNORE);
driver = new FirefoxDriver(options);
}
@Test
void canListenToWindowBrowsingContextCreatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextCreated(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.WINDOW).getWindowHandle();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
}
}
@Test
void canListenToTabBrowsingContextCreatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextCreated(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.TAB).getWindowHandle();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
}
}
@Test
void canListenToDomContentLoadedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onDomContentLoaded(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToBrowsingContextLoadedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextLoaded(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToNavigationStartedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
inspector.onNavigationStarted(future::complete);
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("bidi/logEntryAdded"));
}
}
@Test
void canListenToFragmentNavigatedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<NavigationInfo> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
context.navigate("https://www.selenium.dev/selenium/web/linked_image.html", ReadinessState.COMPLETE);
inspector.onFragmentNavigated(future::complete);
context.navigate("https://www.selenium.dev/selenium/web/linked_image.html#linkToAnchorOnThisPage", ReadinessState.COMPLETE);
NavigationInfo navigationInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertTrue(navigationInfo.getUrl().contains("linkToAnchorOnThisPage"));
}
}
@Test
void canListenToUserPromptOpenedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<UserPromptOpened> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
inspector.onUserPromptOpened(future::complete);
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("alert")).click();
UserPromptOpened userPromptOpened = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(context.getId(), userPromptOpened.getBrowsingContextId());
}
}
@Test
void canListenToUserPromptClosedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<UserPromptClosed> future = new CompletableFuture<>();
BrowsingContext context = new BrowsingContext(driver, driver.getWindowHandle());
inspector.onUserPromptClosed(future::complete);
driver.get("https://www.selenium.dev/selenium/web/alerts.html");
driver.findElement(By.id("prompt")).click();
context.handleUserPrompt(true, "selenium");
UserPromptClosed userPromptClosed = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(context.getId(), userPromptClosed.getBrowsingContextId());
}
}
@Test
void canListenToBrowsingContextDestroyedEvent()
throws ExecutionException, InterruptedException, TimeoutException {
try (BrowsingContextInspector inspector = new BrowsingContextInspector(driver)) {
CompletableFuture<BrowsingContextInfo> future = new CompletableFuture<>();
inspector.onBrowsingContextDestroyed(future::complete);
String windowHandle = driver.switchTo().newWindow(WindowType.WINDOW).getWindowHandle();
driver.close();
BrowsingContextInfo browsingContextInfo = future.get(5, TimeUnit.SECONDS);
Assertions.assertEquals(windowHandle, browsingContextInfo.getId());
Assertions.assertTrue(browsingContextInfo.getUrl().contains("about:blank"));
}
}
}
TaskCompletionSource<ContextDestroyedEventArgs> tcs = new();
await bidi.BrowsingContext.ContextDestroyed.SubscribeAsync(args => tcs.TrySetResult(args));
await context.CloseAsync();
var contextInfo = await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.IsNotNull(contextInfo);
Assert.AreEqual(context, contextInfo.Context);
Console.WriteLine(contextInfo);/examples/dotnet/SeleniumDocs/BiDi/BrowsingContext/BrowsingContextTest.Event.BrowsingContextDestroyed.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.BiDi.BrowsingContext;
using System;
using System.Threading.Tasks;
namespace SeleniumDocs.BiDi.BrowsingContext;
partial class BrowsingContextTest
{
[TestMethod]
public async Task BrowsingContextDestroyedEvent()
{
TaskCompletionSource<ContextDestroyedEventArgs> tcs = new();
await bidi.BrowsingContext.ContextDestroyed.SubscribeAsync(args => tcs.TrySetResult(args));
await context.CloseAsync();
var contextInfo = await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.IsNotNull(contextInfo);
Assert.AreEqual(context, contextInfo.Context);
Console.WriteLine(contextInfo);
}
}
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextDestroyed((entry) => {
contextInfo = entry
})
await driver.switchTo().newWindow('window')
const windowHandle = await driver.getWindowHandle()
await driver.close()/examples/javascript/test/bidirectional/browsingContextInspector.spec.js
const BrowsingContextInspector = require("selenium-webdriver/bidi/browsingContextInspector");
const BrowsingContext = require("selenium-webdriver/bidi/browsingContext");
const assert = require("assert");
const firefox = require('selenium-webdriver/firefox');
const {Builder} = require("selenium-webdriver");
describe('Browsing Context Inspector', function () {
let driver
beforeEach(async function () {
driver = new Builder()
.forBrowser('firefox')
.setFirefoxOptions(new firefox.Options().enableBidi())
.build()
})
afterEach(async function () {
await driver.quit()
})
it('can listen to window browsing context created event', async function () {
let contextInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextCreated((entry) => {
contextInfo = entry
})
await driver.switchTo().newWindow('window')
const windowHandle = await driver.getWindowHandle()
assert.equal(contextInfo.id, windowHandle)
assert.equal(contextInfo.url, 'about:blank')
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.parentBrowsingContext, null)
})
it('can listen to tab browsing context created event', async function () {
let contextInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextCreated((entry) => {
contextInfo = entry
})
await driver.switchTo().newWindow('tab')
const tabHandle = await driver.getWindowHandle()
assert.equal(contextInfo.id, tabHandle)
assert.equal(contextInfo.url, 'about:blank')
assert.equal(contextInfo.children, null)
assert.equal(contextInfo.parentBrowsingContext, null)
})
it('can listen to dom content loaded event', async function () {
const browsingContextInspector = await BrowsingContextInspector(driver)
let navigationInfo = null
await browsingContextInspector.onDomContentLoaded((entry) => {
navigationInfo = entry
})
const browsingContext = await BrowsingContext(driver, {
browsingContextId: await driver.getWindowHandle(),
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
assert.equal(navigationInfo.browsingContextId, browsingContext.id)
assert.strictEqual(navigationInfo.url.includes('/bidi/logEntryAdded.html'), true)
})
it('can listen to browsing context loaded event', async function () {
let navigationInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextLoaded((entry) => {
navigationInfo = entry
})
const browsingContext = await BrowsingContext(driver, {
browsingContextId: await driver.getWindowHandle(),
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/bidi/logEntryAdded.html', 'complete')
assert.equal(navigationInfo.browsingContextId, browsingContext.id)
assert.strictEqual(navigationInfo.url.includes('/bidi/logEntryAdded.html'), true)
})
it('can listen to fragment navigated event', async function () {
let navigationInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
const browsingContext = await BrowsingContext(driver, {
browsingContextId: await driver.getWindowHandle(),
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/linked_image.html', 'complete')
await browsingContextInspector.onFragmentNavigated((entry) => {
navigationInfo = entry
})
await browsingContext.navigate('https://www.selenium.dev/selenium/web/linked_image.html#linkToAnchorOnThisPage', 'complete')
assert.equal(navigationInfo.browsingContextId, browsingContext.id)
assert.strictEqual(navigationInfo.url.includes('linkToAnchorOnThisPage'), true)
})
it('can listen to browsing context destroyed event', async function () {
let contextInfo = null
const browsingContextInspector = await BrowsingContextInspector(driver)
await browsingContextInspector.onBrowsingContextDestroyed((entry) => {
contextInfo = entry
})
await driver.switchTo().newWindow('window')
const windowHandle = await driver.getWindowHandle()
await driver.close()
assert.equal(contextInfo.id, windowHandle)
assert.equal(contextInfo.url, 'about:blank')
assert.equal(contextInfo.children.length, 0)
assert.equal(contextInfo.parentBrowsingContext, null)
})
})




