This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Browser interactions

Get browser information

Coletar título

Você pode ler o título da página atual no navegador:

      String title = driver.getTitle();
Show full example
package dev.selenium.interactions;

import dev.selenium.BaseChromeTest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.Cookie;
import java.util.Set;

public class InteractionsTest extends BaseChromeTest {
  @Test
  public void getTitle() {
    try {
      driver.get("https://www.selenium.dev/");
      // get title
      String title = driver.getTitle();
      Assertions.assertEquals(title, "Selenium");
    } finally {
      driver.quit();
    }
  }
  @Test
  public void getCurrentUrl() {
    try {
      driver.get("https://www.selenium.dev/");
      // get current url
      String url = driver.getCurrentUrl();
      Assertions.assertEquals(url, "https://www.selenium.dev/");
    } finally {
      driver.quit();
    }
  }
}
title = driver.title
Show full example
from selenium import webdriver

driver = webdriver.Chrome()

driver.get("https://www.selenium.dev")

title = driver.title
assert title == "Selenium"

url = driver.current_url
assert url == "https://www.selenium.dev/"

driver.quit()
            String title = driver.Title;
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocumentation.SeleniumInteractions
{
    [TestClass]
    public class InteractionsTest
    {
        [TestMethod]
        public void TestInteractions()
        {
            WebDriver driver = new ChromeDriver();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);

            // Navigate to Url
            driver.Url="https://www.selenium.dev/";
            //GetTitle
            String title = driver.Title;
            Assert.AreEqual(title, "Selenium");

            //GetCurrentURL
            String url = driver.Url;
            Assert.AreEqual(url, "https://www.selenium.dev/");

            //quitting driver
            driver.Quit(); //close all windows
        }
    }
}
    current_title = driver.title
Show full example
require 'spec_helper'

RSpec.describe 'Browser' do
  let(:driver) { start_session }

  it 'gets the current title' do
    driver.navigate.to 'https://www.selenium.dev/'
    current_title = driver.title
    expect(current_title).to eq 'Selenium'
  end

  it 'gets the current url' do
    driver.navigate.to 'https://www.selenium.dev/'
    current_url = driver.current_url
    expect(current_url).to eq 'https://www.selenium.dev/'
  end
end
    let title = await driver.getTitle();
Show full example
const {Builder } = require('selenium-webdriver');
const assert = require("node:assert");

describe('Interactions', function () {
  let driver;

  before(async function () {
    driver = new Builder()
      .forBrowser('chrome')
      .build();
  });

  after(async () => await driver.quit());

  it('Should be able to get title and current url', async function () {
    const url = 'https://www.selenium.dev/';
    await driver.get(url);

    //Get Current title
    let title = await driver.getTitle();
    assert.equal(title, "Selenium");

    //Get Current url
    let currentUrl = await driver.getCurrentUrl();
    assert.equal(currentUrl, url);
  });
});
driver.title

Coletar a URL atual

Você pode ler a URL atual na barra de endereço do navegador usando:

      String url = driver.getCurrentUrl();
Show full example
package dev.selenium.interactions;

import dev.selenium.BaseChromeTest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.Cookie;
import java.util.Set;

public class InteractionsTest extends BaseChromeTest {
  @Test
  public void getTitle() {
    try {
      driver.get("https://www.selenium.dev/");
      // get title
      String title = driver.getTitle();
      Assertions.assertEquals(title, "Selenium");
    } finally {
      driver.quit();
    }
  }
  @Test
  public void getCurrentUrl() {
    try {
      driver.get("https://www.selenium.dev/");
      // get current url
      String url = driver.getCurrentUrl();
      Assertions.assertEquals(url, "https://www.selenium.dev/");
    } finally {
      driver.quit();
    }
  }
}
url = driver.current_url
Show full example
from selenium import webdriver

driver = webdriver.Chrome()

driver.get("https://www.selenium.dev")

title = driver.title
assert title == "Selenium"

url = driver.current_url
assert url == "https://www.selenium.dev/"

driver.quit()
            String url = driver.Url;
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocumentation.SeleniumInteractions
{
    [TestClass]
    public class InteractionsTest
    {
        [TestMethod]
        public void TestInteractions()
        {
            WebDriver driver = new ChromeDriver();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);

            // Navigate to Url
            driver.Url="https://www.selenium.dev/";
            //GetTitle
            String title = driver.Title;
            Assert.AreEqual(title, "Selenium");

            //GetCurrentURL
            String url = driver.Url;
            Assert.AreEqual(url, "https://www.selenium.dev/");

            //quitting driver
            driver.Quit(); //close all windows
        }
    }
}
    current_url = driver.current_url
Show full example
require 'spec_helper'

RSpec.describe 'Browser' do
  let(:driver) { start_session }

  it 'gets the current title' do
    driver.navigate.to 'https://www.selenium.dev/'
    current_title = driver.title
    expect(current_title).to eq 'Selenium'
  end

  it 'gets the current url' do
    driver.navigate.to 'https://www.selenium.dev/'
    current_url = driver.current_url
    expect(current_url).to eq 'https://www.selenium.dev/'
  end
end
    let currentUrl = await driver.getCurrentUrl();
Show full example
const {Builder } = require('selenium-webdriver');
const assert = require("node:assert");

describe('Interactions', function () {
  let driver;

  before(async function () {
    driver = new Builder()
      .forBrowser('chrome')
      .build();
  });

  after(async () => await driver.quit());

  it('Should be able to get title and current url', async function () {
    const url = 'https://www.selenium.dev/';
    await driver.get(url);

    //Get Current title
    let title = await driver.getTitle();
    assert.equal(title, "Selenium");

    //Get Current url
    let currentUrl = await driver.getCurrentUrl();
    assert.equal(currentUrl, url);
  });
});
driver.currentUrl

1 - Browser navigation

A primeira coisa que você vai querer fazer depois de iniciar um navegador é abrir o seu site. Isso pode ser feito em uma única linha, utilize o seguinte comando:

        //Convenient
        driver.get("https://selenium.dev");
            
        //Longer way
        driver.navigate().to("https://selenium.dev");
Show full example
package dev.selenium.interactions;

import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class NavigationTest {
    @Test
    public void navigateBrowser() {
        
        WebDriver driver = new ChromeDriver();
      
        //Convenient
        driver.get("https://selenium.dev");
            
        //Longer way
        driver.navigate().to("https://selenium.dev");
        String title = driver.getTitle();
        assertEquals(title, "Selenium");
        
        //Back
        driver.navigate().back();
        title = driver.getTitle();
        assertEquals(title, "Selenium");
        
        //Forward
        driver.navigate().forward();
        title = driver.getTitle();
        assertEquals(title, "Selenium");

        //Refresh
        driver.navigate().refresh();
        title = driver.getTitle();
        assertEquals(title, "Selenium");

        driver.quit();
    }
}
driver.get("https://www.selenium.dev/selenium/web/index.html")
Show full example
from selenium import webdriver

driver = webdriver.Chrome()

driver.get("https://www.selenium.dev")
driver.get("https://www.selenium.dev/selenium/web/index.html")

title = driver.title
assert title == "Index of Available Pages"

driver.back()
title = driver.title
assert title == "Selenium"

driver.forward()
title = driver.title
assert title == "Index of Available Pages"

driver.refresh()
title = driver.title
assert title == "Index of Available Pages"

driver.quit()
            //Convenient
            driver.Url = "https://selenium.dev";
            //Longer
            driver.Navigate().GoToUrl("https://selenium.dev");
Show full example
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocumentation.SeleniumInteractions
{
    [TestClass]
    public class NavigationTest
    {
        [TestMethod]
        public void TestNavigationCommands()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);

            //Convenient
            driver.Url = "https://selenium.dev";
            //Longer
            driver.Navigate().GoToUrl("https://selenium.dev");
            var title = driver.Title;
            Assert.AreEqual("Selenium", title);

            //Back
            driver.Navigate().Back();
            title = driver.Title;
            Assert.AreEqual("Selenium", title);

            //Forward
            driver.Navigate().Forward();
            title = driver.Title;
            Assert.AreEqual("Selenium", title);

            //Refresh
            driver.Navigate().Refresh();
            title = driver.Title;
            Assert.AreEqual("Selenium", title);

            //Quit the browser
            driver.Quit();
        }
    }
}
    driver.navigate.to 'https://www.selenium.dev/'
    driver.get 'https://www.selenium.dev/'
    expect(driver.current_url).to eq 'https://www.selenium.dev/'
Show full example
require 'spec_helper'

RSpec.describe 'Browser' do
  let(:driver) { start_session }

  it 'navigates to a page' do
    driver.navigate.to 'https://www.selenium.dev/'
    driver.get 'https://www.selenium.dev/'
    expect(driver.current_url).to eq 'https://www.selenium.dev/'
  end

  it 'navigates back' do
    driver.navigate.to 'https://www.selenium.dev/'
    driver.navigate.to 'https://www.selenium.dev/selenium/web/inputs.html'
    driver.navigate.back
    expect(driver.current_url).to eq 'https://www.selenium.dev/'
  end

  it 'navigates forward' do
    driver.navigate.to 'https://www.selenium.dev/'
    driver.navigate.to 'https://www.selenium.dev/selenium/web/inputs.html'
    driver.navigate.back
    driver.navigate.forward
    expect(driver.current_url).to eq 'https://www.selenium.dev/selenium/web/inputs.html'
  end

  it 'refreshes the page' do
    driver.navigate.to 'https://www.selenium.dev/'
    driver.navigate.refresh
    expect(driver.current_url).to eq 'https://www.selenium.dev/'
  end
end
    //Convenient
    await driver.get('https://www.selenium.dev');

    //Longer way
    await driver.navigate().to("https://www.selenium.dev/selenium/web/index.html");
Show full example
const {Builder } = require('selenium-webdriver');
const assert = require("node:assert");

describe('Interactions - Navigation', function () {
  let driver;

  before(async function () {
    driver = new Builder()
      .forBrowser('chrome')
      .build();
  });

  after(async () => await driver.quit());

  it('Browser navigation test', async function () {
    //Convenient
    await driver.get('https://www.selenium.dev');

    //Longer way
    await driver.navigate().to("https://www.selenium.dev/selenium/web/index.html");
    let title = await driver.getTitle();
    assert.equal(title, "Index of Available Pages");

    //Back
    await driver.navigate().back();
    title = await driver.getTitle();
    assert.equal(title, "Selenium");

    //Forward
    await driver.navigate().forward();
    title = await driver.getTitle();
    assert.equal(title, "Index of Available Pages");

    //Refresh
    await driver.navigate().refresh();
    title = await driver.getTitle();
    assert.equal(title, "Index of Available Pages");
  });
});
//Convenient
driver.get("https://selenium.dev")

//Longer way
driver.navigate().to("https://selenium.dev")
  

Voltar

Pressionando o botão Voltar do navegador:

        //Back
        driver.navigate().back();
Show full example
package dev.selenium.interactions;

import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class NavigationTest {
    @Test
    public void navigateBrowser() {
        
        WebDriver driver = new ChromeDriver();
      
        //Convenient
        driver.get("https://selenium.dev");
            
        //Longer way
        driver.navigate().to("https://selenium.dev");
        String title = driver.getTitle();
        assertEquals(title, "Selenium");
        
        //Back
        driver.navigate().back();
        title = driver.getTitle();
        assertEquals(title, "Selenium");
        
        //Forward
        driver.navigate().forward();
        title = driver.getTitle();
        assertEquals(title, "Selenium");

        //Refresh
        driver.navigate().refresh();
        title = driver.getTitle();
        assertEquals(title, "Selenium");

        driver.quit();
    }
}
driver.back()
Show full example
from selenium import webdriver

driver = webdriver.Chrome()

driver.get("https://www.selenium.dev")
driver.get("https://www.selenium.dev/selenium/web/index.html")

title = driver.title
assert title == "Index of Available Pages"

driver.back()
title = driver.title
assert title == "Selenium"

driver.forward()
title = driver.title
assert title == "Index of Available Pages"

driver.refresh()
title = driver.title
assert title == "Index of Available Pages"

driver.quit()
            //Back
             driver.Navigate().Back();
Show full example
using System;
 using Microsoft.VisualStudio.TestTools.UnitTesting;
 using OpenQA.Selenium;
 using OpenQA.Selenium.Chrome;
 
 namespace SeleniumDocumentation.SeleniumInteractions
 {
     [TestClass]
     public class NavigationTest
     {
         [TestMethod]
         public void TestNavigationCommands()
         {
             IWebDriver driver = new ChromeDriver();
             driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
 
             //Convenient
             driver.Url = "https://selenium.dev";
             //Longer
             driver.Navigate().GoToUrl("https://selenium.dev");
             var title = driver.Title;
             Assert.AreEqual("Selenium", title);
 
             //Back
             driver.Navigate().Back();
             title = driver.Title;
             Assert.AreEqual("Selenium", title);
 
             //Forward
             driver.Navigate().Forward();
             title = driver.Title;
             Assert.AreEqual("Selenium", title);
 
             //Refresh
             driver.Navigate().Refresh();
             title = driver.Title;
             Assert.AreEqual("Selenium", title);
 
             //Quit the browser
             driver.Quit();
         }
     }
 }
 
    driver.navigate.back
Show full example
require 'spec_helper'

RSpec.describe 'Browser' do
  let(:driver) { start_session }

  it 'navigates to a page' do
    driver.navigate.to 'https://www.selenium.dev/'
    driver.get 'https://www.selenium.dev/'
    expect(driver.current_url).to eq 'https://www.selenium.dev/'
  end

  it 'navigates back' do
    driver.navigate.to 'https://www.selenium.dev/'
    driver.navigate.to 'https://www.selenium.dev/selenium/web/inputs.html'
    driver.navigate.back
    expect(driver.current_url).to eq 'https://www.selenium.dev/'
  end

  it 'navigates forward' do
    driver.navigate.to 'https://www.selenium.dev/'
    driver.navigate.to 'https://www.selenium.dev/selenium/web/inputs.html'
    driver.navigate.back
    driver.navigate.forward
    expect(driver.current_url).to eq 'https://www.selenium.dev/selenium/web/inputs.html'
  end

  it 'refreshes the page' do
    driver.navigate.to 'https://www.selenium.dev/'
    driver.navigate.refresh
    expect(driver.current_url).to eq 'https://www.selenium.dev/'
  end
end
    //Back
    await driver.navigate().back();
Show full example
const {Builder } = require('selenium-webdriver');
const assert = require("node:assert");

describe('Interactions - Navigation', function () {
  let driver;

  before(async function () {
    driver = new Builder()
      .forBrowser('chrome')
      .build();
  });

  after(async () => await driver.quit());

  it('Browser navigation test', async function () {
    //Convenient
    await driver.get('https://www.selenium.dev');

    //Longer way
    await driver.navigate().to("https://www.selenium.dev/selenium/web/index.html");
    let title = await driver.getTitle();
    assert.equal(title, "Index of Available Pages");

    //Back
    await driver.navigate().back();
    title = await driver.getTitle();
    assert.equal(title, "Selenium");

    //Forward
    await driver.navigate().forward();
    title = await driver.getTitle();
    assert.equal(title, "Index of Available Pages");

    //Refresh
    await driver.navigate().refresh();
    title = await driver.getTitle();
    assert.equal(title, "Index of Available Pages");
  });
});
driver.navigate().back() 

Avançar

Pressionando o botão Avançar do navegador:

        //Forward
        driver.navigate().forward();
Show full example
package dev.selenium.interactions;

import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class NavigationTest {
    @Test
    public void navigateBrowser() {
        
        WebDriver driver = new ChromeDriver();
      
        //Convenient
        driver.get("https://selenium.dev");
            
        //Longer way
        driver.navigate().to("https://selenium.dev");
        String title = driver.getTitle();
        assertEquals(title, "Selenium");
        
        //Back
        driver.navigate().back();
        title = driver.getTitle();
        assertEquals(title, "Selenium");
        
        //Forward
        driver.navigate().forward();
        title = driver.getTitle();
        assertEquals(title, "Selenium");

        //Refresh
        driver.navigate().refresh();
        title = driver.getTitle();
        assertEquals(title, "Selenium");

        driver.quit();
    }
}
driver.forward()
Show full example
from selenium import webdriver

driver = webdriver.Chrome()

driver.get("https://www.selenium.dev")
driver.get("https://www.selenium.dev/selenium/web/index.html")

title = driver.title
assert title == "Index of Available Pages"

driver.back()
title = driver.title
assert title == "Selenium"

driver.forward()
title = driver.title
assert title == "Index of Available Pages"

driver.refresh()
title = driver.title
assert title == "Index of Available Pages"

driver.quit()
            //Forward
             driver.Navigate().Forward();
Show full example
using System;
 using Microsoft.VisualStudio.TestTools.UnitTesting;
 using OpenQA.Selenium;
 using OpenQA.Selenium.Chrome;
 
 namespace SeleniumDocumentation.SeleniumInteractions
 {
     [TestClass]
     public class NavigationTest
     {
         [TestMethod]
         public void TestNavigationCommands()
         {
             IWebDriver driver = new ChromeDriver();
             driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
 
             //Convenient
             driver.Url = "https://selenium.dev";
             //Longer
             driver.Navigate().GoToUrl("https://selenium.dev");
             var title = driver.Title;
             Assert.AreEqual("Selenium", title);
 
             //Back
             driver.Navigate().Back();
             title = driver.Title;
             Assert.AreEqual("Selenium", title);
 
             //Forward
             driver.Navigate().Forward();
             title = driver.Title;
             Assert.AreEqual("Selenium", title);
 
             //Refresh
             driver.Navigate().Refresh();
             title = driver.Title;
             Assert.AreEqual("Selenium", title);
 
             //Quit the browser
             driver.Quit();
         }
     }
 }
 
    driver.navigate.forward
Show full example
require 'spec_helper'

RSpec.describe 'Browser' do
  let(:driver) { start_session }

  it 'navigates to a page' do
    driver.navigate.to 'https://www.selenium.dev/'
    driver.get 'https://www.selenium.dev/'
    expect(driver.current_url).to eq 'https://www.selenium.dev/'
  end

  it 'navigates back' do
    driver.navigate.to 'https://www.selenium.dev/'
    driver.navigate.to 'https://www.selenium.dev/selenium/web/inputs.html'
    driver.navigate.back
    expect(driver.current_url).to eq 'https://www.selenium.dev/'
  end

  it 'navigates forward' do
    driver.navigate.to 'https://www.selenium.dev/'
    driver.navigate.to 'https://www.selenium.dev/selenium/web/inputs.html'
    driver.navigate.back
    driver.navigate.forward
    expect(driver.current_url).to eq 'https://www.selenium.dev/selenium/web/inputs.html'
  end

  it 'refreshes the page' do
    driver.navigate.to 'https://www.selenium.dev/'
    driver.navigate.refresh
    expect(driver.current_url).to eq 'https://www.selenium.dev/'
  end
end
    //Forward
    await driver.navigate().forward();
Show full example
const {Builder } = require('selenium-webdriver');
const assert = require("node:assert");

describe('Interactions - Navigation', function () {
  let driver;

  before(async function () {
    driver = new Builder()
      .forBrowser('chrome')
      .build();
  });

  after(async () => await driver.quit());

  it('Browser navigation test', async function () {
    //Convenient
    await driver.get('https://www.selenium.dev');

    //Longer way
    await driver.navigate().to("https://www.selenium.dev/selenium/web/index.html");
    let title = await driver.getTitle();
    assert.equal(title, "Index of Available Pages");

    //Back
    await driver.navigate().back();
    title = await driver.getTitle();
    assert.equal(title, "Selenium");

    //Forward
    await driver.navigate().forward();
    title = await driver.getTitle();
    assert.equal(title, "Index of Available Pages");

    //Refresh
    await driver.navigate().refresh();
    title = await driver.getTitle();
    assert.equal(title, "Index of Available Pages");
  });
});
driver.navigate().forward()

Atualizar

Atualizando a página atual:

        //Refresh
        driver.navigate().refresh();
Show full example
package dev.selenium.interactions;

import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class NavigationTest {
    @Test
    public void navigateBrowser() {
        
        WebDriver driver = new ChromeDriver();
      
        //Convenient
        driver.get("https://selenium.dev");
            
        //Longer way
        driver.navigate().to("https://selenium.dev");
        String title = driver.getTitle();
        assertEquals(title, "Selenium");
        
        //Back
        driver.navigate().back();
        title = driver.getTitle();
        assertEquals(title, "Selenium");
        
        //Forward
        driver.navigate().forward();
        title = driver.getTitle();
        assertEquals(title, "Selenium");

        //Refresh
        driver.navigate().refresh();
        title = driver.getTitle();
        assertEquals(title, "Selenium");

        driver.quit();
    }
}
driver.refresh()
Show full example
from selenium import webdriver

driver = webdriver.Chrome()

driver.get("https://www.selenium.dev")
driver.get("https://www.selenium.dev/selenium/web/index.html")

title = driver.title
assert title == "Index of Available Pages"

driver.back()
title = driver.title
assert title == "Selenium"

driver.forward()
title = driver.title
assert title == "Index of Available Pages"

driver.refresh()
title = driver.title
assert title == "Index of Available Pages"

driver.quit()
            //Refresh
             driver.Navigate().Refresh();
Show full example
using System;
 using Microsoft.VisualStudio.TestTools.UnitTesting;
 using OpenQA.Selenium;
 using OpenQA.Selenium.Chrome;
 
 namespace SeleniumDocumentation.SeleniumInteractions
 {
     [TestClass]
     public class NavigationTest
     {
         [TestMethod]
         public void TestNavigationCommands()
         {
             IWebDriver driver = new ChromeDriver();
             driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
 
             //Convenient
             driver.Url = "https://selenium.dev";
             //Longer
             driver.Navigate().GoToUrl("https://selenium.dev");
             var title = driver.Title;
             Assert.AreEqual("Selenium", title);
 
             //Back
             driver.Navigate().Back();
             title = driver.Title;
             Assert.AreEqual("Selenium", title);
 
             //Forward
             driver.Navigate().Forward();
             title = driver.Title;
             Assert.AreEqual("Selenium", title);
 
             //Refresh
             driver.Navigate().Refresh();
             title = driver.Title;
             Assert.AreEqual("Selenium", title);
 
             //Quit the browser
             driver.Quit();
         }
     }
 }
 
    driver.navigate.refresh
Show full example
require 'spec_helper'

RSpec.describe 'Browser' do
  let(:driver) { start_session }

  it 'navigates to a page' do
    driver.navigate.to 'https://www.selenium.dev/'
    driver.get 'https://www.selenium.dev/'
    expect(driver.current_url).to eq 'https://www.selenium.dev/'
  end

  it 'navigates back' do
    driver.navigate.to 'https://www.selenium.dev/'
    driver.navigate.to 'https://www.selenium.dev/selenium/web/inputs.html'
    driver.navigate.back
    expect(driver.current_url).to eq 'https://www.selenium.dev/'
  end

  it 'navigates forward' do
    driver.navigate.to 'https://www.selenium.dev/'
    driver.navigate.to 'https://www.selenium.dev/selenium/web/inputs.html'
    driver.navigate.back
    driver.navigate.forward
    expect(driver.current_url).to eq 'https://www.selenium.dev/selenium/web/inputs.html'
  end

  it 'refreshes the page' do
    driver.navigate.to 'https://www.selenium.dev/'
    driver.navigate.refresh
    expect(driver.current_url).to eq 'https://www.selenium.dev/'
  end
end
    //Refresh
    await driver.navigate().refresh();
Show full example
const {Builder } = require('selenium-webdriver');
const assert = require("node:assert");

describe('Interactions - Navigation', function () {
  let driver;

  before(async function () {
    driver = new Builder()
      .forBrowser('chrome')
      .build();
  });

  after(async () => await driver.quit());

  it('Browser navigation test', async function () {
    //Convenient
    await driver.get('https://www.selenium.dev');

    //Longer way
    await driver.navigate().to("https://www.selenium.dev/selenium/web/index.html");
    let title = await driver.getTitle();
    assert.equal(title, "Index of Available Pages");

    //Back
    await driver.navigate().back();
    title = await driver.getTitle();
    assert.equal(title, "Selenium");

    //Forward
    await driver.navigate().forward();
    title = await driver.getTitle();
    assert.equal(title, "Index of Available Pages");

    //Refresh
    await driver.navigate().refresh();
    title = await driver.getTitle();
    assert.equal(title, "Index of Available Pages");
  });
});
driver.navigate().refresh()

2 - Alertas, prompts e confirmações JavaScript

WebDriver fornece uma API para trabalhar com os três tipos nativos de mensagens pop-up oferecidas pelo JavaScript. Esses pop-ups são estilizados pelo navegador e oferecem personalização limitada.

Alertas

O mais simples deles é referido como um alerta, que mostra um mensagem personalizada e um único botão que dispensa o alerta, rotulado na maioria dos navegadores como OK. Ele também pode ser dispensado na maioria dos navegadores pressionando o botão Fechar, mas isso sempre fará a mesma coisa que o botão OK. Veja um exemplo de alerta .

O WebDriver pode obter o texto do pop-up e aceitar ou dispensar esses alertas.

        wait.until(ExpectedConditions.alertIsPresent());

        Alert alert = driver.switchTo().alert();
        //Store the alert text in a variable and verify it
        String text = alert.getText();
        assertEquals(text, "Sample Alert");
        //Press the OK button
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

import dev.selenium.BaseTest;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class AlertsTest extends BaseTest {

    @Test
    public void testForAlerts() throws Exception {

        ChromeOptions chromeOptions = getDefaultChromeOptions();
        chromeOptions.addArguments("disable-search-engine-choice-screen");
        WebDriver driver = new ChromeDriver(chromeOptions);

        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
        driver.manage().window().maximize();
        //Navigate to Url
        driver.get("https://www.selenium.dev/documentation/webdriver/interactions/alerts/");

        //Simple Alert
        //Click the link to activate the alert
        JavascriptExecutor js = (JavascriptExecutor) driver;
        //execute js for alert
        js.executeScript("alert('Sample Alert');");
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        //Wait for the alert to be displayed and store it in a variable
        wait.until(ExpectedConditions.alertIsPresent());

        Alert alert = driver.switchTo().alert();
        //Store the alert text in a variable and verify it
        String text = alert.getText();
        assertEquals(text, "Sample Alert");
        //Press the OK button
        alert.accept();

        //Confirm
        //execute js for confirm
        js.executeScript("confirm('Are you sure?');");
        //Wait for the alert to be displayed
        wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        wait.until(ExpectedConditions.alertIsPresent());


        alert = driver.switchTo().alert();
        //Store the alert text in a variable and verify it
        text = alert.getText();
        assertEquals(text, "Are you sure?");
        //Press the Cancel button
        alert.dismiss();

        //Prompt
        //execute js for prompt
        js.executeScript("prompt('What is your name?');");
        //Wait for the alert to be displayed and store it in a variable
        wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        wait.until(ExpectedConditions.alertIsPresent());

        alert = driver.switchTo().alert();
        //Store the alert text in a variable and verify it
        text = alert.getText();
        assertEquals(text, "What is your name?");
        //Type your message
        alert.sendKeys("Selenium");
        //Press the OK button
        alert.accept();
        //quit the browser
        driver.quit();
    }
}
    element = driver.find_element(By.LINK_TEXT, "See an example alert")
    element.click()

    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    text = alert.text
    alert.accept()
Show full example
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

global url
url = "https://www.selenium.dev/documentation/webdriver/interactions/alerts/"


def test_alert_popup():
    driver = webdriver.Chrome()
    driver.get(url)
    element = driver.find_element(By.LINK_TEXT, "See an example alert")
    element.click()

    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    text = alert.text
    alert.accept()
    assert text == "Sample alert"

    driver.quit()

def test_confirm_popup():
    driver = webdriver.Chrome()
    driver.get(url)
    element = driver.find_element(By.LINK_TEXT, "See a sample confirm")
    driver.execute_script("arguments[0].click();", element)

    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    text = alert.text
    alert.dismiss()
    assert text == "Are you sure?"

    driver.quit()

def test_prompt_popup():
    driver = webdriver.Chrome()
    driver.get(url)
    element = driver.find_element(By.LINK_TEXT, "See a sample prompt")
    driver.execute_script("arguments[0].click();", element)

    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    alert.send_keys("Selenium")
    text = alert.text
    alert.accept()
    assert text == "What is your tool of choice?"
    
    driver.quit()
    # Store the alert reference in a variable
    alert = driver.switch_to.alert

    # Get the text of the alert
    alert.text

    # Press on Cancel button
    alert.dismiss
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Alerts' do
  let(:driver) { start_session }

  before do
    driver.navigate.to 'https://selenium.dev'
  end

  it 'interacts with an alert' do
    driver.execute_script 'alert("Hello, World!")'

    # Store the alert reference in a variable
    alert = driver.switch_to.alert

    # Get the text of the alert
    alert.text

    # Press on Cancel button
    alert.dismiss
  end

  it 'interacts with a confirm' do
    driver.execute_script 'confirm("Are you sure?")'

    # Store the alert reference in a variable
    alert = driver.switch_to.alert

    # Get the text of the alert
    alert.text

    # Press on Cancel button
    alert.dismiss
  end

  it 'interacts with a prompt' do
    driver.execute_script 'prompt("What is your name?")'

    # Store the alert reference in a variable
    alert = driver.switch_to.alert

    # Type a message
    alert.send_keys('selenium')

    # Press on Ok button
    alert.accept
  end
end
        let alert = await driver.switchTo().alert();
        let alertText = await alert.getText();
        await alert.accept();
Show full example

const { By, Builder, until } = require('selenium-webdriver');
const assert = require("node:assert");


describe('Interactions - Alerts', function () {
    let driver;

    before(async function () {
        driver = await new Builder().forBrowser('chrome').build();
    });

    after(async () => await driver.quit());

    it('Should be able to getText from alert and accept', async function () {
        await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
        await driver.findElement(By.id("alert")).click();
        await driver.wait(until.alertIsPresent());
        let alert = await driver.switchTo().alert();
        let alertText = await alert.getText();
        await alert.accept();
        // Verify
        assert.equal(alertText, "cheese");
    });

    it('Should be able to getText from alert and dismiss', async function () {
        await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
        await driver.findElement(By.id("confirm")).click();
        await driver.wait(until.alertIsPresent());
        let alert = await driver.switchTo().alert();
        let alertText = await alert.getText();
        await alert.dismiss();
        // Verify
        assert.equal(alertText, "Are you sure?");
    });

    it('Should be able to enter text in alert prompt', async function () {
        let text = 'Selenium';
        await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
        await driver.findElement(By.id("prompt")).click();
        await driver.wait(until.alertIsPresent());
        let alert = await driver.switchTo().alert();
        //Type your message
        await alert.sendKeys(text);
        await alert.accept();

        let enteredText = await driver.findElement(By.id('text'));
        assert.equal(await enteredText.getText(), text);
    });
});
//Click the link to activate the alert
driver.findElement(By.linkText("See an example alert")).click()

//Wait for the alert to be displayed and store it in a variable
val alert = wait.until(ExpectedConditions.alertIsPresent())

//Store the alert text in a variable
val text = alert.getText()

//Press the OK button
alert.accept()
  

Confirmação

Uma caixa de confirmação é semelhante a um alerta, exceto que o usuário também pode escolher cancelar a mensagem. Veja uma amostra de confirmação .

Este exemplo também mostra uma abordagem diferente para armazenar um alerta:



        alert = driver.switchTo().alert();
        //Store the alert text in a variable and verify it
        text = alert.getText();
        assertEquals(text, "Are you sure?");
        //Press the Cancel button
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

import dev.selenium.BaseTest;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class AlertsTest extends BaseTest {

    @Test
    public void testForAlerts() throws Exception {

        ChromeOptions chromeOptions = getDefaultChromeOptions();
        chromeOptions.addArguments("disable-search-engine-choice-screen");
        WebDriver driver = new ChromeDriver(chromeOptions);

        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
        driver.manage().window().maximize();
        //Navigate to Url
        driver.get("https://www.selenium.dev/documentation/webdriver/interactions/alerts/");

        //Simple Alert
        //Click the link to activate the alert
        JavascriptExecutor js = (JavascriptExecutor) driver;
        //execute js for alert
        js.executeScript("alert('Sample Alert');");
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        //Wait for the alert to be displayed and store it in a variable
        wait.until(ExpectedConditions.alertIsPresent());

        Alert alert = driver.switchTo().alert();
        //Store the alert text in a variable and verify it
        String text = alert.getText();
        assertEquals(text, "Sample Alert");
        //Press the OK button
        alert.accept();

        //Confirm
        //execute js for confirm
        js.executeScript("confirm('Are you sure?');");
        //Wait for the alert to be displayed
        wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        wait.until(ExpectedConditions.alertIsPresent());


        alert = driver.switchTo().alert();
        //Store the alert text in a variable and verify it
        text = alert.getText();
        assertEquals(text, "Are you sure?");
        //Press the Cancel button
        alert.dismiss();

        //Prompt
        //execute js for prompt
        js.executeScript("prompt('What is your name?');");
        //Wait for the alert to be displayed and store it in a variable
        wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        wait.until(ExpectedConditions.alertIsPresent());

        alert = driver.switchTo().alert();
        //Store the alert text in a variable and verify it
        text = alert.getText();
        assertEquals(text, "What is your name?");
        //Type your message
        alert.sendKeys("Selenium");
        //Press the OK button
        alert.accept();
        //quit the browser
        driver.quit();
    }
}
    element = driver.find_element(By.LINK_TEXT, "See a sample confirm")
    driver.execute_script("arguments[0].click();", element)

    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    text = alert.text
    alert.dismiss()
Show full example
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

global url
url = "https://www.selenium.dev/documentation/webdriver/interactions/alerts/"


def test_alert_popup():
    driver = webdriver.Chrome()
    driver.get(url)
    element = driver.find_element(By.LINK_TEXT, "See an example alert")
    element.click()

    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    text = alert.text
    alert.accept()
    assert text == "Sample alert"

    driver.quit()

def test_confirm_popup():
    driver = webdriver.Chrome()
    driver.get(url)
    element = driver.find_element(By.LINK_TEXT, "See a sample confirm")
    driver.execute_script("arguments[0].click();", element)

    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    text = alert.text
    alert.dismiss()
    assert text == "Are you sure?"

    driver.quit()

def test_prompt_popup():
    driver = webdriver.Chrome()
    driver.get(url)
    element = driver.find_element(By.LINK_TEXT, "See a sample prompt")
    driver.execute_script("arguments[0].click();", element)

    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    alert.send_keys("Selenium")
    text = alert.text
    alert.accept()
    assert text == "What is your tool of choice?"
    
    driver.quit()
//Click the link to activate the alert
driver.FindElement(By.LinkText("See a sample confirm")).Click();

//Wait for the alert to be displayed
wait.Until(ExpectedConditions.AlertIsPresent());

//Store the alert in a variable
IAlert alert = driver.SwitchTo().Alert();

//Store the alert in a variable for reuse
string text = alert.Text;

//Press the Cancel button
alert.Dismiss();
  
    # Store the alert reference in a variable
    alert = driver.switch_to.alert

    # Get the text of the alert
    alert.text

    # Press on Cancel button
    alert.dismiss
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Alerts' do
  let(:driver) { start_session }

  before do
    driver.navigate.to 'https://selenium.dev'
  end

  it 'interacts with an alert' do
    driver.execute_script 'alert("Hello, World!")'

    # Store the alert reference in a variable
    alert = driver.switch_to.alert

    # Get the text of the alert
    alert.text

    # Press on Cancel button
    alert.dismiss
  end

  it 'interacts with a confirm' do
    driver.execute_script 'confirm("Are you sure?")'

    # Store the alert reference in a variable
    alert = driver.switch_to.alert

    # Get the text of the alert
    alert.text

    # Press on Cancel button
    alert.dismiss
  end

  it 'interacts with a prompt' do
    driver.execute_script 'prompt("What is your name?")'

    # Store the alert reference in a variable
    alert = driver.switch_to.alert

    # Type a message
    alert.send_keys('selenium')

    # Press on Ok button
    alert.accept
  end
end
        let alert = await driver.switchTo().alert();
        let alertText = await alert.getText();
        await alert.dismiss();
Show full example

const { By, Builder, until } = require('selenium-webdriver');
const assert = require("node:assert");


describe('Interactions - Alerts', function () {
    let driver;

    before(async function () {
        driver = await new Builder().forBrowser('chrome').build();
    });

    after(async () => await driver.quit());

    it('Should be able to getText from alert and accept', async function () {
        await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
        await driver.findElement(By.id("alert")).click();
        await driver.wait(until.alertIsPresent());
        let alert = await driver.switchTo().alert();
        let alertText = await alert.getText();
        await alert.accept();
        // Verify
        assert.equal(alertText, "cheese");
    });

    it('Should be able to getText from alert and dismiss', async function () {
        await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
        await driver.findElement(By.id("confirm")).click();
        await driver.wait(until.alertIsPresent());
        let alert = await driver.switchTo().alert();
        let alertText = await alert.getText();
        await alert.dismiss();
        // Verify
        assert.equal(alertText, "Are you sure?");
    });

    it('Should be able to enter text in alert prompt', async function () {
        let text = 'Selenium';
        await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
        await driver.findElement(By.id("prompt")).click();
        await driver.wait(until.alertIsPresent());
        let alert = await driver.switchTo().alert();
        //Type your message
        await alert.sendKeys(text);
        await alert.accept();

        let enteredText = await driver.findElement(By.id('text'));
        assert.equal(await enteredText.getText(), text);
    });
});
//Click the link to activate the alert
driver.findElement(By.linkText("See a sample confirm")).click()

//Wait for the alert to be displayed
wait.until(ExpectedConditions.alertIsPresent())

//Store the alert in a variable
val alert = driver.switchTo().alert()

//Store the alert in a variable for reuse
val text = alert.text

//Press the Cancel button
alert.dismiss()
  

Prompt

Os prompts são semelhantes às caixas de confirmação, exceto que também incluem um texto de entrada. Semelhante a trabalhar com elementos de formulário, você pode usar o sendKeys do WebDriver para preencher uma resposta. Isso substituirá completamente o espaço de texto de exemplo. Pressionar o botão Cancelar não enviará nenhum texto. Veja um exemplo de prompt .

        wait.until(ExpectedConditions.alertIsPresent());

        alert = driver.switchTo().alert();
        //Store the alert text in a variable and verify it
        text = alert.getText();
        assertEquals(text, "What is your name?");
        //Type your message
        alert.sendKeys("Selenium");
        //Press the OK button
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

import dev.selenium.BaseTest;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class AlertsTest extends BaseTest {

    @Test
    public void testForAlerts() throws Exception {

        ChromeOptions chromeOptions = getDefaultChromeOptions();
        chromeOptions.addArguments("disable-search-engine-choice-screen");
        WebDriver driver = new ChromeDriver(chromeOptions);

        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
        driver.manage().window().maximize();
        //Navigate to Url
        driver.get("https://www.selenium.dev/documentation/webdriver/interactions/alerts/");

        //Simple Alert
        //Click the link to activate the alert
        JavascriptExecutor js = (JavascriptExecutor) driver;
        //execute js for alert
        js.executeScript("alert('Sample Alert');");
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        //Wait for the alert to be displayed and store it in a variable
        wait.until(ExpectedConditions.alertIsPresent());

        Alert alert = driver.switchTo().alert();
        //Store the alert text in a variable and verify it
        String text = alert.getText();
        assertEquals(text, "Sample Alert");
        //Press the OK button
        alert.accept();

        //Confirm
        //execute js for confirm
        js.executeScript("confirm('Are you sure?');");
        //Wait for the alert to be displayed
        wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        wait.until(ExpectedConditions.alertIsPresent());


        alert = driver.switchTo().alert();
        //Store the alert text in a variable and verify it
        text = alert.getText();
        assertEquals(text, "Are you sure?");
        //Press the Cancel button
        alert.dismiss();

        //Prompt
        //execute js for prompt
        js.executeScript("prompt('What is your name?');");
        //Wait for the alert to be displayed and store it in a variable
        wait = new WebDriverWait(driver, Duration.ofSeconds(30));
        wait.until(ExpectedConditions.alertIsPresent());

        alert = driver.switchTo().alert();
        //Store the alert text in a variable and verify it
        text = alert.getText();
        assertEquals(text, "What is your name?");
        //Type your message
        alert.sendKeys("Selenium");
        //Press the OK button
        alert.accept();
        //quit the browser
        driver.quit();
    }
}
    element = driver.find_element(By.LINK_TEXT, "See a sample prompt")
    driver.execute_script("arguments[0].click();", element)

    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    alert.send_keys("Selenium")
    text = alert.text
    alert.accept()
Show full example
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

global url
url = "https://www.selenium.dev/documentation/webdriver/interactions/alerts/"


def test_alert_popup():
    driver = webdriver.Chrome()
    driver.get(url)
    element = driver.find_element(By.LINK_TEXT, "See an example alert")
    element.click()

    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    text = alert.text
    alert.accept()
    assert text == "Sample alert"

    driver.quit()

def test_confirm_popup():
    driver = webdriver.Chrome()
    driver.get(url)
    element = driver.find_element(By.LINK_TEXT, "See a sample confirm")
    driver.execute_script("arguments[0].click();", element)

    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    text = alert.text
    alert.dismiss()
    assert text == "Are you sure?"

    driver.quit()

def test_prompt_popup():
    driver = webdriver.Chrome()
    driver.get(url)
    element = driver.find_element(By.LINK_TEXT, "See a sample prompt")
    driver.execute_script("arguments[0].click();", element)

    wait = WebDriverWait(driver, timeout=2)
    alert = wait.until(lambda d : d.switch_to.alert)
    alert.send_keys("Selenium")
    text = alert.text
    alert.accept()
    assert text == "What is your tool of choice?"
    
    driver.quit()
//Click the link to activate the alert
driver.FindElement(By.LinkText("See a sample prompt")).Click();

//Wait for the alert to be displayed and store it in a variable
IAlert alert = wait.Until(ExpectedConditions.AlertIsPresent());

//Type your message
alert.SendKeys("Selenium");

//Press the OK button
alert.Accept();
  
    # Store the alert reference in a variable
    alert = driver.switch_to.alert

    # Type a message
    alert.send_keys('selenium')

    # Press on Ok button
    alert.accept
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Alerts' do
  let(:driver) { start_session }

  before do
    driver.navigate.to 'https://selenium.dev'
  end

  it 'interacts with an alert' do
    driver.execute_script 'alert("Hello, World!")'

    # Store the alert reference in a variable
    alert = driver.switch_to.alert

    # Get the text of the alert
    alert.text

    # Press on Cancel button
    alert.dismiss
  end

  it 'interacts with a confirm' do
    driver.execute_script 'confirm("Are you sure?")'

    # Store the alert reference in a variable
    alert = driver.switch_to.alert

    # Get the text of the alert
    alert.text

    # Press on Cancel button
    alert.dismiss
  end

  it 'interacts with a prompt' do
    driver.execute_script 'prompt("What is your name?")'

    # Store the alert reference in a variable
    alert = driver.switch_to.alert

    # Type a message
    alert.send_keys('selenium')

    # Press on Ok button
    alert.accept
  end
end
        let alert = await driver.switchTo().alert();
        //Type your message
        await alert.sendKeys(text);
        await alert.accept();
Show full example

const { By, Builder, until } = require('selenium-webdriver');
const assert = require("node:assert");


describe('Interactions - Alerts', function () {
    let driver;

    before(async function () {
        driver = await new Builder().forBrowser('chrome').build();
    });

    after(async () => await driver.quit());

    it('Should be able to getText from alert and accept', async function () {
        await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
        await driver.findElement(By.id("alert")).click();
        await driver.wait(until.alertIsPresent());
        let alert = await driver.switchTo().alert();
        let alertText = await alert.getText();
        await alert.accept();
        // Verify
        assert.equal(alertText, "cheese");
    });

    it('Should be able to getText from alert and dismiss', async function () {
        await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
        await driver.findElement(By.id("confirm")).click();
        await driver.wait(until.alertIsPresent());
        let alert = await driver.switchTo().alert();
        let alertText = await alert.getText();
        await alert.dismiss();
        // Verify
        assert.equal(alertText, "Are you sure?");
    });

    it('Should be able to enter text in alert prompt', async function () {
        let text = 'Selenium';
        await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
        await driver.findElement(By.id("prompt")).click();
        await driver.wait(until.alertIsPresent());
        let alert = await driver.switchTo().alert();
        //Type your message
        await alert.sendKeys(text);
        await alert.accept();

        let enteredText = await driver.findElement(By.id('text'));
        assert.equal(await enteredText.getText(), text);
    });
});
//Click the link to activate the alert
driver.findElement(By.linkText("See a sample prompt")).click()

//Wait for the alert to be displayed and store it in a variable
val alert = wait.until(ExpectedConditions.alertIsPresent())

//Type your message
alert.sendKeys("Selenium")

//Press the OK button
alert.accept()
  

3 - Trabalhando com cookies

Um cookie é um pequeno pedaço de dado enviado de um site e armazenado no seu computador. Os cookies são usados principalmente para reconhecer o usuário e carregar as informações armazenadas.

A API WebDriver fornece uma maneira de interagir com cookies com métodos integrados:

É usado para adicionar um cookie ao contexto de navegação atual. Add Cookie aceita apenas um conjunto de objetos JSON serializáveis definidos. Aqui é o link para a lista de valores-chave JSON aceitos.

Em primeiro lugar, você precisa estar no domínio para qual o cookie será valido. Se você está tentando predefinir cookies antes de começar a interagir com um site e sua página inicial é grande / demora um pouco para carregar uma alternativa é encontrar uma página menor no site (normalmente a página 404 é pequena, por exemplo http://example.com/some404page)

	      driver.get("https://www.selenium.dev/selenium/web/blank.html");
	      // Add cookie into current browser context
	      driver.manage().addCookie(new Cookie("key", "value"));
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Set;

public class CookiesTest {

	WebDriver driver = new ChromeDriver();
	@Test
	  public void addCookie() {
	      driver.get("https://www.selenium.dev/selenium/web/blank.html");
	      // Add cookie into current browser context
	      driver.manage().addCookie(new Cookie("key", "value"));
	      driver.quit();
	}
	    @Test
	    public void getNamedCookie() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        // Add cookie into current browser context
	        driver.manage().addCookie(new Cookie("foo", "bar"));
	        // Get cookie details with named cookie 'foo'
	        Cookie cookie = driver.manage().getCookieNamed("foo");
	        Assertions.assertEquals(cookie.getValue(), "bar");
	     
	        driver.quit();
	      }
	  

	    @Test
	    public void getAllCookies() {
	      
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        // Add cookies into current browser context
	        driver.manage().addCookie(new Cookie("test1", "cookie1"));
	        driver.manage().addCookie(new Cookie("test2", "cookie2"));
	        // Get cookies
	        Set<Cookie> cookies = driver.manage().getCookies();
	         for (Cookie cookie : cookies) {
	            if (cookie.getName().equals("test1")) {
	                Assertions.assertEquals(cookie.getValue(), "cookie1");
	            }

	            if (cookie.getName().equals("test2")) {
	                Assertions.assertEquals(cookie.getValue(), "cookie2");
	            }
	         }
	         driver.quit();
	      }
	   

	    @Test
	    public void deleteCookieNamed() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        driver.manage().addCookie(new Cookie("test1", "cookie1"));
	        // delete cookie named
	        driver.manage().deleteCookieNamed("test1");
	        driver.quit();
	    }

	    @Test
	    public void deleteCookieObject() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        Cookie cookie = new Cookie("test2", "cookie2");
	        driver.manage().addCookie(cookie);
	        /*
	        Selenium Java bindings also provides a way to delete
	        cookie by passing cookie object of current browsing context
	        */
	        driver.manage().deleteCookie(cookie);
	      
	        driver.quit();
	      }
	  

	    @Test
	    public void deleteAllCookies() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        // Add cookies into current browser context
	        driver.manage().addCookie(new Cookie("test1", "cookie1"));
	        driver.manage().addCookie(new Cookie("test2", "cookie2"));
	        // Delete All cookies
	        driver.manage().deleteAllCookies();
	     
	        driver.quit();
	      }

		  @Test
		  public void sameSiteCookie() {
		    driver.get("http://www.example.com");

     	    Cookie cookie = new Cookie.Builder("key", "value").sameSite("Strict").build();
            Cookie cookie1 = new Cookie.Builder("key", "value").sameSite("Lax").build();

            driver.manage().addCookie(cookie);
            driver.manage().addCookie(cookie1);

            System.out.println(cookie.getSameSite());
            System.out.println(cookie1.getSameSite());

			driver.quit();
		  }
}
    driver = webdriver.Chrome()
    driver.get("http://www.example.com")

    # Adds the cookie into current browser context
    driver.add_cookie({"name": "key", "value": "value"})
Show full example
from selenium import webdriver


def add_cookie():
    driver = webdriver.Chrome()
    driver.get("http://www.example.com")

    # Adds the cookie into current browser context
    driver.add_cookie({"name": "key", "value": "value"})


def get_named_cookie():
    driver = webdriver.Chrome()
    driver.get("http://www.example.com")

    # Adds the cookie into current browser context
    driver.add_cookie({"name": "foo", "value": "bar"})

    # Get cookie details with named cookie 'foo'
    print(driver.get_cookie("foo"))


def get_all_cookies():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Get all available cookies
    print(driver.get_cookies())

def delete_cookie():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Delete cookie with name 'test1'
    driver.delete_cookie("test1")


def delete_all_cookies():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Delete all cookies
    driver.delete_all_cookies()


def same_side_cookie_attr():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    # Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'
    driver.add_cookie({"name": "foo", "value": "value", "sameSite": "Strict"})
    driver.add_cookie({"name": "foo1", "value": "value", "sameSite": "Lax"})

    cookie1 = driver.get_cookie("foo")
    cookie2 = driver.get_cookie("foo1")

    print(cookie1)
    print(cookie2)
         driver.Url="https://www.selenium.dev/selenium/web/blank.html";
         // Add cookie into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("key", "value"));
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocs.Interactions{

[TestClass]
public class CookiesTest{
     
    WebDriver driver = new ChromeDriver();

     [TestMethod]
      public void addCookie(){
         driver.Url="https://www.selenium.dev/selenium/web/blank.html";
         // Add cookie into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("key", "value"));
         driver.Quit();
     }
     
     [TestMethod]
     public void getNamedCookie(){  
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         // Add cookie into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("foo", "bar"));
         // Get cookie details with named cookie 'foo'
         Cookie cookie = driver.Manage().Cookies.GetCookieNamed("foo");
         Assert.AreEqual(cookie.Value, "bar");
         driver.Quit();
     }

     [TestMethod]
     public void getAllCookies(){
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         // Add cookies into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("test1", "cookie1"));
         driver.Manage().Cookies.AddCookie(new Cookie("test2", "cookie2"));
         // Get cookies
         var cookies = driver.Manage().Cookies.AllCookies;
         foreach (var cookie in cookies){
             if (cookie.Name.Equals("test1")){
                 Assert.AreEqual("cookie1", cookie.Value);
             }
             if (cookie.Name.Equals("test2")){
                 Assert.AreEqual("cookie2", cookie.Value);
             }
         }
         driver.Quit();
     }
     
     [TestMethod]
     public void deleteCookieNamed(){
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         driver.Manage().Cookies.AddCookie(new Cookie("test1", "cookie1"));
         // delete cookie named
         driver.Manage().Cookies.DeleteCookieNamed("test1");
         driver.Quit();
     }

     [TestMethod]
     public void deleteCookieObject(){
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         Cookie cookie = new Cookie("test2", "cookie2");
         driver.Manage().Cookies.AddCookie(cookie);
         /*
      Selenium CSharp bindings also provides a way to delete
      cookie by passing cookie object of current browsing context
      */
         driver.Manage().Cookies.DeleteCookie(cookie);
         driver.Quit();
     }
     
     [TestMethod]
     public void deleteAllCookies(){
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         // Add cookies into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("test1", "cookie1"));
         driver.Manage().Cookies.AddCookie(new Cookie("test2", "cookie2"));
         // Delete All cookies
         driver.Manage().Cookies.DeleteAllCookies();
         driver.Quit();
     }
    }
}
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :chrome

begin
  driver.get 'https://www.example.com'
  
  # Adds the cookie into current browser context
  driver.manage.add_cookie(name: "key", value: "value")
ensure
  driver.quit
end
  
Show full example

  const {Browser, Builder} = require("selenium-webdriver");
  
  
  describe('Cookies', function() {
    let driver;
  
    before(async function() {
      driver = new Builder()
        .forBrowser(Browser.CHROME)
        .build();
    });
  
    after(async () => await driver.quit());
  
    it('Create a cookie', async function() {
      await driver.get('https://www.selenium.dev/selenium/web/blank.html');
  
      // set a cookie on the current domain
      await driver.manage().addCookie({ name: 'key', value: 'value' });
    });
  
    it('Create cookies with sameSite', async function() {
      await driver.get('https://www.selenium.dev/selenium/web/blank.html');
  
      // set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'
      await driver.manage().addCookie({ name: 'key', value: 'value', sameSite: 'Strict' });
      await driver.manage().addCookie({ name: 'key', value: 'value', sameSite: 'Lax' });
    });
  
    it('Read cookie', async function() {
      await driver.get('https://www.selenium.dev/selenium/web/blank.html');
  
      // set a cookie on the current domain
      await driver.manage().addCookie({ name: 'foo', value: 'bar' });
  
      // Get cookie details with named cookie 'foo'
      await driver.manage().getCookie('foo').then(function(cookie) {
        console.log('cookie details => ', cookie);
      });
    });
  
    it('Read all cookies', async function() {
      await driver.get('https://www.selenium.dev/selenium/web/blank.html');
  
      // Add few cookies
      await driver.manage().addCookie({ name: 'test1', value: 'cookie1' });
      await driver.manage().addCookie({ name: 'test2', value: 'cookie2' });
  
      // Get all Available cookies
      await driver.manage().getCookies().then(function(cookies) {
        console.log('cookie details => ', cookies);
      });
    });
  
    it('Delete a cookie', async function() {
      await driver.get('https://www.selenium.dev/selenium/web/blank.html');
  
      // Add few cookies
      await driver.manage().addCookie({ name: 'test1', value: 'cookie1' });
      await driver.manage().addCookie({ name: 'test2', value: 'cookie2' });
  
      // Delete a cookie with name 'test1'
      await driver.manage().deleteCookie('test1');
  
      // Get all Available cookies
      await driver.manage().getCookies().then(function(cookies) {
        console.log('cookie details => ', cookies);
      });
    });
  
    it('Delete all cookies', async function() {
      await driver.get('https://www.selenium.dev/selenium/web/blank.html');
  
      // Add few cookies
      await driver.manage().addCookie({ name: 'test1', value: 'cookie1' });
      await driver.manage().addCookie({ name: 'test2', value: 'cookie2' });
  
      // Delete all cookies
      await driver.manage().deleteAllCookies();
    });
  });
import org.openqa.selenium.Cookie
import org.openqa.selenium.chrome.ChromeDriver

fun main() {
    val driver = ChromeDriver()
    try {
        driver.get("https://example.com")

        // Adds the cookie into current browser context
        driver.manage().addCookie(Cookie("key", "value"))
    } finally {
        driver.quit()
    }
}
  

Retorna os dados do cookie serializado correspondentes ao nome do cookie entre todos os cookies associados.

	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        // Add cookie into current browser context
	        driver.manage().addCookie(new Cookie("foo", "bar"));
	        // Get cookie details with named cookie 'foo'
	        Cookie cookie = driver.manage().getCookieNamed("foo");
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Set;

public class CookiesTest {

	WebDriver driver = new ChromeDriver();
	@Test
	  public void addCookie() {
	      driver.get("https://www.selenium.dev/selenium/web/blank.html");
	      // Add cookie into current browser context
	      driver.manage().addCookie(new Cookie("key", "value"));
	      driver.quit();
	}
	    @Test
	    public void getNamedCookie() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        // Add cookie into current browser context
	        driver.manage().addCookie(new Cookie("foo", "bar"));
	        // Get cookie details with named cookie 'foo'
	        Cookie cookie = driver.manage().getCookieNamed("foo");
	        Assertions.assertEquals(cookie.getValue(), "bar");
	     
	        driver.quit();
	      }
	  

	    @Test
	    public void getAllCookies() {
	      
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        // Add cookies into current browser context
	        driver.manage().addCookie(new Cookie("test1", "cookie1"));
	        driver.manage().addCookie(new Cookie("test2", "cookie2"));
	        // Get cookies
	        Set<Cookie> cookies = driver.manage().getCookies();
	         for (Cookie cookie : cookies) {
	            if (cookie.getName().equals("test1")) {
	                Assertions.assertEquals(cookie.getValue(), "cookie1");
	            }

	            if (cookie.getName().equals("test2")) {
	                Assertions.assertEquals(cookie.getValue(), "cookie2");
	            }
	         }
	         driver.quit();
	      }
	   

	    @Test
	    public void deleteCookieNamed() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        driver.manage().addCookie(new Cookie("test1", "cookie1"));
	        // delete cookie named
	        driver.manage().deleteCookieNamed("test1");
	        driver.quit();
	    }

	    @Test
	    public void deleteCookieObject() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        Cookie cookie = new Cookie("test2", "cookie2");
	        driver.manage().addCookie(cookie);
	        /*
	        Selenium Java bindings also provides a way to delete
	        cookie by passing cookie object of current browsing context
	        */
	        driver.manage().deleteCookie(cookie);
	      
	        driver.quit();
	      }
	  

	    @Test
	    public void deleteAllCookies() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        // Add cookies into current browser context
	        driver.manage().addCookie(new Cookie("test1", "cookie1"));
	        driver.manage().addCookie(new Cookie("test2", "cookie2"));
	        // Delete All cookies
	        driver.manage().deleteAllCookies();
	     
	        driver.quit();
	      }

		  @Test
		  public void sameSiteCookie() {
		    driver.get("http://www.example.com");

     	    Cookie cookie = new Cookie.Builder("key", "value").sameSite("Strict").build();
            Cookie cookie1 = new Cookie.Builder("key", "value").sameSite("Lax").build();

            driver.manage().addCookie(cookie);
            driver.manage().addCookie(cookie1);

            System.out.println(cookie.getSameSite());
            System.out.println(cookie1.getSameSite());

			driver.quit();
		  }
}
    driver = webdriver.Chrome()
    driver.get("http://www.example.com")

    # Adds the cookie into current browser context
    driver.add_cookie({"name": "foo", "value": "bar"})

    # Get cookie details with named cookie 'foo'
    print(driver.get_cookie("foo"))
Show full example
from selenium import webdriver


def add_cookie():
    driver = webdriver.Chrome()
    driver.get("http://www.example.com")

    # Adds the cookie into current browser context
    driver.add_cookie({"name": "key", "value": "value"})


def get_named_cookie():
    driver = webdriver.Chrome()
    driver.get("http://www.example.com")

    # Adds the cookie into current browser context
    driver.add_cookie({"name": "foo", "value": "bar"})

    # Get cookie details with named cookie 'foo'
    print(driver.get_cookie("foo"))


def get_all_cookies():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Get all available cookies
    print(driver.get_cookies())

def delete_cookie():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Delete cookie with name 'test1'
    driver.delete_cookie("test1")


def delete_all_cookies():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Delete all cookies
    driver.delete_all_cookies()


def same_side_cookie_attr():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    # Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'
    driver.add_cookie({"name": "foo", "value": "value", "sameSite": "Strict"})
    driver.add_cookie({"name": "foo1", "value": "value", "sameSite": "Lax"})

    cookie1 = driver.get_cookie("foo")
    cookie2 = driver.get_cookie("foo1")

    print(cookie1)
    print(cookie2)
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         // Add cookie into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("foo", "bar"));
         // Get cookie details with named cookie 'foo'
         Cookie cookie = driver.Manage().Cookies.GetCookieNamed("foo");
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocs.Interactions{

[TestClass]
public class CookiesTest{
     
    WebDriver driver = new ChromeDriver();

     [TestMethod]
      public void addCookie(){
         driver.Url="https://www.selenium.dev/selenium/web/blank.html";
         // Add cookie into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("key", "value"));
         driver.Quit();
     }
     
     [TestMethod]
     public void getNamedCookie(){  
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         // Add cookie into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("foo", "bar"));
         // Get cookie details with named cookie 'foo'
         Cookie cookie = driver.Manage().Cookies.GetCookieNamed("foo");
         Assert.AreEqual(cookie.Value, "bar");
         driver.Quit();
     }

     [TestMethod]
     public void getAllCookies(){
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         // Add cookies into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("test1", "cookie1"));
         driver.Manage().Cookies.AddCookie(new Cookie("test2", "cookie2"));
         // Get cookies
         var cookies = driver.Manage().Cookies.AllCookies;
         foreach (var cookie in cookies){
             if (cookie.Name.Equals("test1")){
                 Assert.AreEqual("cookie1", cookie.Value);
             }
             if (cookie.Name.Equals("test2")){
                 Assert.AreEqual("cookie2", cookie.Value);
             }
         }
         driver.Quit();
     }
     
     [TestMethod]
     public void deleteCookieNamed(){
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         driver.Manage().Cookies.AddCookie(new Cookie("test1", "cookie1"));
         // delete cookie named
         driver.Manage().Cookies.DeleteCookieNamed("test1");
         driver.Quit();
     }

     [TestMethod]
     public void deleteCookieObject(){
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         Cookie cookie = new Cookie("test2", "cookie2");
         driver.Manage().Cookies.AddCookie(cookie);
         /*
      Selenium CSharp bindings also provides a way to delete
      cookie by passing cookie object of current browsing context
      */
         driver.Manage().Cookies.DeleteCookie(cookie);
         driver.Quit();
     }
     
     [TestMethod]
     public void deleteAllCookies(){
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         // Add cookies into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("test1", "cookie1"));
         driver.Manage().Cookies.AddCookie(new Cookie("test2", "cookie2"));
         // Delete All cookies
         driver.Manage().Cookies.DeleteAllCookies();
         driver.Quit();
     }
    }
}
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :chrome

begin
  driver.get 'https://www.example.com'
  driver.manage.add_cookie(name: "foo", value: "bar")

  # Get cookie details with named cookie 'foo'
  puts driver.manage.cookie_named('foo')
ensure
  driver.quit
end
  
    await driver.manage().addCookie({ name: 'foo', value: 'bar' });

    // Get cookie details with named cookie 'foo'
    await driver.manage().getCookie('foo').then(function(cookie) {
Show full example

const {Browser, Builder} = require("selenium-webdriver");


describe('Cookies', function() {
  let driver;

  before(async function() {
    driver = new Builder()
      .forBrowser(Browser.CHROME)
      .build();
  });

  after(async () => await driver.quit());

  it('Create a cookie', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // set a cookie on the current domain
    await driver.manage().addCookie({ name: 'key', value: 'value' });
  });

  it('Create cookies with sameSite', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'
    await driver.manage().addCookie({ name: 'key', value: 'value', sameSite: 'Strict' });
    await driver.manage().addCookie({ name: 'key', value: 'value', sameSite: 'Lax' });
  });

  it('Read cookie', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // set a cookie on the current domain
    await driver.manage().addCookie({ name: 'foo', value: 'bar' });

    // Get cookie details with named cookie 'foo'
    await driver.manage().getCookie('foo').then(function(cookie) {
      console.log('cookie details => ', cookie);
    });
  });

  it('Read all cookies', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // Add few cookies
    await driver.manage().addCookie({ name: 'test1', value: 'cookie1' });
    await driver.manage().addCookie({ name: 'test2', value: 'cookie2' });

    // Get all Available cookies
    await driver.manage().getCookies().then(function(cookies) {
      console.log('cookie details => ', cookies);
    });
  });

  it('Delete a cookie', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // Add few cookies
    await driver.manage().addCookie({ name: 'test1', value: 'cookie1' });
    await driver.manage().addCookie({ name: 'test2', value: 'cookie2' });

    // Delete a cookie with name 'test1'
    await driver.manage().deleteCookie('test1');

    // Get all Available cookies
    await driver.manage().getCookies().then(function(cookies) {
      console.log('cookie details => ', cookies);
    });
  });

  it('Delete all cookies', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // Add few cookies
    await driver.manage().addCookie({ name: 'test1', value: 'cookie1' });
    await driver.manage().addCookie({ name: 'test2', value: 'cookie2' });

    // Delete all cookies
    await driver.manage().deleteAllCookies();
  });
});
import org.openqa.selenium.Cookie
import org.openqa.selenium.chrome.ChromeDriver

fun main() {
    val driver = ChromeDriver()
    try {
        driver.get("https://example.com")
        driver.manage().addCookie(Cookie("foo", "bar"))

        // Get cookie details with named cookie 'foo'
        val cookie = driver.manage().getCookieNamed("foo")
        println(cookie)
    } finally {
        driver.quit()
    }
}  
  

Get All Cookies

Retorna ‘dados de cookie serializados com sucesso’ para o contexto de navegação atual. Se o navegador não estiver mais disponível, ele retornará um erro.

	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        // Add cookies into current browser context
	        driver.manage().addCookie(new Cookie("test1", "cookie1"));
	        driver.manage().addCookie(new Cookie("test2", "cookie2"));
	        // Get cookies
	        Set<Cookie> cookies = driver.manage().getCookies();
	         for (Cookie cookie : cookies) {
	            if (cookie.getName().equals("test1")) {
	                Assertions.assertEquals(cookie.getValue(), "cookie1");
	            }

	            if (cookie.getName().equals("test2")) {
	                Assertions.assertEquals(cookie.getValue(), "cookie2");
	            }
	         }
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Set;

public class CookiesTest {

	WebDriver driver = new ChromeDriver();
	@Test
	  public void addCookie() {
	      driver.get("https://www.selenium.dev/selenium/web/blank.html");
	      // Add cookie into current browser context
	      driver.manage().addCookie(new Cookie("key", "value"));
	      driver.quit();
	}
	    @Test
	    public void getNamedCookie() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        // Add cookie into current browser context
	        driver.manage().addCookie(new Cookie("foo", "bar"));
	        // Get cookie details with named cookie 'foo'
	        Cookie cookie = driver.manage().getCookieNamed("foo");
	        Assertions.assertEquals(cookie.getValue(), "bar");
	     
	        driver.quit();
	      }
	  

	    @Test
	    public void getAllCookies() {
	      
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        // Add cookies into current browser context
	        driver.manage().addCookie(new Cookie("test1", "cookie1"));
	        driver.manage().addCookie(new Cookie("test2", "cookie2"));
	        // Get cookies
	        Set<Cookie> cookies = driver.manage().getCookies();
	         for (Cookie cookie : cookies) {
	            if (cookie.getName().equals("test1")) {
	                Assertions.assertEquals(cookie.getValue(), "cookie1");
	            }

	            if (cookie.getName().equals("test2")) {
	                Assertions.assertEquals(cookie.getValue(), "cookie2");
	            }
	         }
	         driver.quit();
	      }
	   

	    @Test
	    public void deleteCookieNamed() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        driver.manage().addCookie(new Cookie("test1", "cookie1"));
	        // delete cookie named
	        driver.manage().deleteCookieNamed("test1");
	        driver.quit();
	    }

	    @Test
	    public void deleteCookieObject() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        Cookie cookie = new Cookie("test2", "cookie2");
	        driver.manage().addCookie(cookie);
	        /*
	        Selenium Java bindings also provides a way to delete
	        cookie by passing cookie object of current browsing context
	        */
	        driver.manage().deleteCookie(cookie);
	      
	        driver.quit();
	      }
	  

	    @Test
	    public void deleteAllCookies() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        // Add cookies into current browser context
	        driver.manage().addCookie(new Cookie("test1", "cookie1"));
	        driver.manage().addCookie(new Cookie("test2", "cookie2"));
	        // Delete All cookies
	        driver.manage().deleteAllCookies();
	     
	        driver.quit();
	      }

		  @Test
		  public void sameSiteCookie() {
		    driver.get("http://www.example.com");

     	    Cookie cookie = new Cookie.Builder("key", "value").sameSite("Strict").build();
            Cookie cookie1 = new Cookie.Builder("key", "value").sameSite("Lax").build();

            driver.manage().addCookie(cookie);
            driver.manage().addCookie(cookie1);

            System.out.println(cookie.getSameSite());
            System.out.println(cookie1.getSameSite());

			driver.quit();
		  }
}
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Get all available cookies
    print(driver.get_cookies())
Show full example
from selenium import webdriver


def add_cookie():
    driver = webdriver.Chrome()
    driver.get("http://www.example.com")

    # Adds the cookie into current browser context
    driver.add_cookie({"name": "key", "value": "value"})


def get_named_cookie():
    driver = webdriver.Chrome()
    driver.get("http://www.example.com")

    # Adds the cookie into current browser context
    driver.add_cookie({"name": "foo", "value": "bar"})

    # Get cookie details with named cookie 'foo'
    print(driver.get_cookie("foo"))


def get_all_cookies():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Get all available cookies
    print(driver.get_cookies())

def delete_cookie():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Delete cookie with name 'test1'
    driver.delete_cookie("test1")


def delete_all_cookies():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Delete all cookies
    driver.delete_all_cookies()


def same_side_cookie_attr():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    # Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'
    driver.add_cookie({"name": "foo", "value": "value", "sameSite": "Strict"})
    driver.add_cookie({"name": "foo1", "value": "value", "sameSite": "Lax"})

    cookie1 = driver.get_cookie("foo")
    cookie2 = driver.get_cookie("foo1")

    print(cookie1)
    print(cookie2)
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         // Add cookies into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("test1", "cookie1"));
         driver.Manage().Cookies.AddCookie(new Cookie("test2", "cookie2"));
         // Get cookies
         var cookies = driver.Manage().Cookies.AllCookies;
         foreach (var cookie in cookies){
             if (cookie.Name.Equals("test1")){
                 Assert.AreEqual("cookie1", cookie.Value);
             }
             if (cookie.Name.Equals("test2")){
                 Assert.AreEqual("cookie2", cookie.Value);
             }
         }
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocs.Interactions{

[TestClass]
public class CookiesTest{
     
    WebDriver driver = new ChromeDriver();

     [TestMethod]
      public void addCookie(){
         driver.Url="https://www.selenium.dev/selenium/web/blank.html";
         // Add cookie into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("key", "value"));
         driver.Quit();
     }
     
     [TestMethod]
     public void getNamedCookie(){  
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         // Add cookie into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("foo", "bar"));
         // Get cookie details with named cookie 'foo'
         Cookie cookie = driver.Manage().Cookies.GetCookieNamed("foo");
         Assert.AreEqual(cookie.Value, "bar");
         driver.Quit();
     }

     [TestMethod]
     public void getAllCookies(){
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         // Add cookies into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("test1", "cookie1"));
         driver.Manage().Cookies.AddCookie(new Cookie("test2", "cookie2"));
         // Get cookies
         var cookies = driver.Manage().Cookies.AllCookies;
         foreach (var cookie in cookies){
             if (cookie.Name.Equals("test1")){
                 Assert.AreEqual("cookie1", cookie.Value);
             }
             if (cookie.Name.Equals("test2")){
                 Assert.AreEqual("cookie2", cookie.Value);
             }
         }
         driver.Quit();
     }
     
     [TestMethod]
     public void deleteCookieNamed(){
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         driver.Manage().Cookies.AddCookie(new Cookie("test1", "cookie1"));
         // delete cookie named
         driver.Manage().Cookies.DeleteCookieNamed("test1");
         driver.Quit();
     }

     [TestMethod]
     public void deleteCookieObject(){
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         Cookie cookie = new Cookie("test2", "cookie2");
         driver.Manage().Cookies.AddCookie(cookie);
         /*
      Selenium CSharp bindings also provides a way to delete
      cookie by passing cookie object of current browsing context
      */
         driver.Manage().Cookies.DeleteCookie(cookie);
         driver.Quit();
     }
     
     [TestMethod]
     public void deleteAllCookies(){
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         // Add cookies into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("test1", "cookie1"));
         driver.Manage().Cookies.AddCookie(new Cookie("test2", "cookie2"));
         // Delete All cookies
         driver.Manage().Cookies.DeleteAllCookies();
         driver.Quit();
     }
    }
}
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :chrome

begin
  driver.get 'https://www.example.com'
  driver.manage.add_cookie(name: "test1", value: "cookie1")
  driver.manage.add_cookie(name: "test2", value: "cookie2")

  # Get all available cookies
  puts driver.manage.all_cookies
ensure
  driver.quit
end
  

    // Get all Available cookies
    await driver.manage().getCookies().then(function(cookies) {
Show full example

const {Browser, Builder} = require("selenium-webdriver");


describe('Cookies', function() {
  let driver;

  before(async function() {
    driver = new Builder()
      .forBrowser(Browser.CHROME)
      .build();
  });

  after(async () => await driver.quit());

  it('Create a cookie', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // set a cookie on the current domain
    await driver.manage().addCookie({ name: 'key', value: 'value' });
  });

  it('Create cookies with sameSite', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'
    await driver.manage().addCookie({ name: 'key', value: 'value', sameSite: 'Strict' });
    await driver.manage().addCookie({ name: 'key', value: 'value', sameSite: 'Lax' });
  });

  it('Read cookie', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // set a cookie on the current domain
    await driver.manage().addCookie({ name: 'foo', value: 'bar' });

    // Get cookie details with named cookie 'foo'
    await driver.manage().getCookie('foo').then(function(cookie) {
      console.log('cookie details => ', cookie);
    });
  });

  it('Read all cookies', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // Add few cookies
    await driver.manage().addCookie({ name: 'test1', value: 'cookie1' });
    await driver.manage().addCookie({ name: 'test2', value: 'cookie2' });

    // Get all Available cookies
    await driver.manage().getCookies().then(function(cookies) {
      console.log('cookie details => ', cookies);
    });
  });

  it('Delete a cookie', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // Add few cookies
    await driver.manage().addCookie({ name: 'test1', value: 'cookie1' });
    await driver.manage().addCookie({ name: 'test2', value: 'cookie2' });

    // Delete a cookie with name 'test1'
    await driver.manage().deleteCookie('test1');

    // Get all Available cookies
    await driver.manage().getCookies().then(function(cookies) {
      console.log('cookie details => ', cookies);
    });
  });

  it('Delete all cookies', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // Add few cookies
    await driver.manage().addCookie({ name: 'test1', value: 'cookie1' });
    await driver.manage().addCookie({ name: 'test2', value: 'cookie2' });

    // Delete all cookies
    await driver.manage().deleteAllCookies();
  });
});
import org.openqa.selenium.Cookie
import org.openqa.selenium.chrome.ChromeDriver

fun main() {
    val driver = ChromeDriver()
    try {
        driver.get("https://example.com")
        driver.manage().addCookie(Cookie("test1", "cookie1"))
        driver.manage().addCookie(Cookie("test2", "cookie2"))

        // Get All available cookies
        val cookies = driver.manage().cookies
        println(cookies)
    } finally {
        driver.quit()
    }
}  
  

Exclui os dados do cookie que correspondem ao nome do cookie fornecido.

	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        driver.manage().addCookie(new Cookie("test1", "cookie1"));
	        // delete cookie named
	        driver.manage().deleteCookieNamed("test1");
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Set;

public class CookiesTest {

	WebDriver driver = new ChromeDriver();
	@Test
	  public void addCookie() {
	      driver.get("https://www.selenium.dev/selenium/web/blank.html");
	      // Add cookie into current browser context
	      driver.manage().addCookie(new Cookie("key", "value"));
	      driver.quit();
	}
	    @Test
	    public void getNamedCookie() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        // Add cookie into current browser context
	        driver.manage().addCookie(new Cookie("foo", "bar"));
	        // Get cookie details with named cookie 'foo'
	        Cookie cookie = driver.manage().getCookieNamed("foo");
	        Assertions.assertEquals(cookie.getValue(), "bar");
	     
	        driver.quit();
	      }
	  

	    @Test
	    public void getAllCookies() {
	      
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        // Add cookies into current browser context
	        driver.manage().addCookie(new Cookie("test1", "cookie1"));
	        driver.manage().addCookie(new Cookie("test2", "cookie2"));
	        // Get cookies
	        Set<Cookie> cookies = driver.manage().getCookies();
	         for (Cookie cookie : cookies) {
	            if (cookie.getName().equals("test1")) {
	                Assertions.assertEquals(cookie.getValue(), "cookie1");
	            }

	            if (cookie.getName().equals("test2")) {
	                Assertions.assertEquals(cookie.getValue(), "cookie2");
	            }
	         }
	         driver.quit();
	      }
	   

	    @Test
	    public void deleteCookieNamed() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        driver.manage().addCookie(new Cookie("test1", "cookie1"));
	        // delete cookie named
	        driver.manage().deleteCookieNamed("test1");
	        driver.quit();
	    }

	    @Test
	    public void deleteCookieObject() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        Cookie cookie = new Cookie("test2", "cookie2");
	        driver.manage().addCookie(cookie);
	        /*
	        Selenium Java bindings also provides a way to delete
	        cookie by passing cookie object of current browsing context
	        */
	        driver.manage().deleteCookie(cookie);
	      
	        driver.quit();
	      }
	  

	    @Test
	    public void deleteAllCookies() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        // Add cookies into current browser context
	        driver.manage().addCookie(new Cookie("test1", "cookie1"));
	        driver.manage().addCookie(new Cookie("test2", "cookie2"));
	        // Delete All cookies
	        driver.manage().deleteAllCookies();
	     
	        driver.quit();
	      }

		  @Test
		  public void sameSiteCookie() {
		    driver.get("http://www.example.com");

     	    Cookie cookie = new Cookie.Builder("key", "value").sameSite("Strict").build();
            Cookie cookie1 = new Cookie.Builder("key", "value").sameSite("Lax").build();

            driver.manage().addCookie(cookie);
            driver.manage().addCookie(cookie1);

            System.out.println(cookie.getSameSite());
            System.out.println(cookie1.getSameSite());

			driver.quit();
		  }
}
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Delete cookie with name 'test1'
    driver.delete_cookie("test1")
Show full example
from selenium import webdriver


def add_cookie():
    driver = webdriver.Chrome()
    driver.get("http://www.example.com")

    # Adds the cookie into current browser context
    driver.add_cookie({"name": "key", "value": "value"})


def get_named_cookie():
    driver = webdriver.Chrome()
    driver.get("http://www.example.com")

    # Adds the cookie into current browser context
    driver.add_cookie({"name": "foo", "value": "bar"})

    # Get cookie details with named cookie 'foo'
    print(driver.get_cookie("foo"))


def get_all_cookies():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Get all available cookies
    print(driver.get_cookies())

def delete_cookie():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Delete cookie with name 'test1'
    driver.delete_cookie("test1")


def delete_all_cookies():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Delete all cookies
    driver.delete_all_cookies()


def same_side_cookie_attr():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    # Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'
    driver.add_cookie({"name": "foo", "value": "value", "sameSite": "Strict"})
    driver.add_cookie({"name": "foo1", "value": "value", "sameSite": "Lax"})

    cookie1 = driver.get_cookie("foo")
    cookie2 = driver.get_cookie("foo1")

    print(cookie1)
    print(cookie2)
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         driver.Manage().Cookies.AddCookie(new Cookie("test1", "cookie1"));
         // delete cookie named
         driver.Manage().Cookies.DeleteCookieNamed("test1");
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocs.Interactions{

[TestClass]
public class CookiesTest{
     
    WebDriver driver = new ChromeDriver();

     [TestMethod]
      public void addCookie(){
         driver.Url="https://www.selenium.dev/selenium/web/blank.html";
         // Add cookie into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("key", "value"));
         driver.Quit();
     }
     
     [TestMethod]
     public void getNamedCookie(){  
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         // Add cookie into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("foo", "bar"));
         // Get cookie details with named cookie 'foo'
         Cookie cookie = driver.Manage().Cookies.GetCookieNamed("foo");
         Assert.AreEqual(cookie.Value, "bar");
         driver.Quit();
     }

     [TestMethod]
     public void getAllCookies(){
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         // Add cookies into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("test1", "cookie1"));
         driver.Manage().Cookies.AddCookie(new Cookie("test2", "cookie2"));
         // Get cookies
         var cookies = driver.Manage().Cookies.AllCookies;
         foreach (var cookie in cookies){
             if (cookie.Name.Equals("test1")){
                 Assert.AreEqual("cookie1", cookie.Value);
             }
             if (cookie.Name.Equals("test2")){
                 Assert.AreEqual("cookie2", cookie.Value);
             }
         }
         driver.Quit();
     }
     
     [TestMethod]
     public void deleteCookieNamed(){
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         driver.Manage().Cookies.AddCookie(new Cookie("test1", "cookie1"));
         // delete cookie named
         driver.Manage().Cookies.DeleteCookieNamed("test1");
         driver.Quit();
     }

     [TestMethod]
     public void deleteCookieObject(){
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         Cookie cookie = new Cookie("test2", "cookie2");
         driver.Manage().Cookies.AddCookie(cookie);
         /*
      Selenium CSharp bindings also provides a way to delete
      cookie by passing cookie object of current browsing context
      */
         driver.Manage().Cookies.DeleteCookie(cookie);
         driver.Quit();
     }
     
     [TestMethod]
     public void deleteAllCookies(){
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         // Add cookies into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("test1", "cookie1"));
         driver.Manage().Cookies.AddCookie(new Cookie("test2", "cookie2"));
         // Delete All cookies
         driver.Manage().Cookies.DeleteAllCookies();
         driver.Quit();
     }
    }
}
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :chrome

begin
  driver.get 'https://www.example.com'
  driver.manage.add_cookie(name: "test1", value: "cookie1")
  driver.manage.add_cookie(name: "test2", value: "cookie2")

  # delete a cookie with name 'test1'
  driver.manage.delete_cookie('test1')
ensure
  driver.quit
end
  
    await driver.manage().addCookie({ name: 'test2', value: 'cookie2' });
Show full example

const {Browser, Builder} = require("selenium-webdriver");


describe('Cookies', function() {
  let driver;

  before(async function() {
    driver = new Builder()
      .forBrowser(Browser.CHROME)
      .build();
  });

  after(async () => await driver.quit());

  it('Create a cookie', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // set a cookie on the current domain
    await driver.manage().addCookie({ name: 'key', value: 'value' });
  });

  it('Create cookies with sameSite', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'
    await driver.manage().addCookie({ name: 'key', value: 'value', sameSite: 'Strict' });
    await driver.manage().addCookie({ name: 'key', value: 'value', sameSite: 'Lax' });
  });

  it('Read cookie', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // set a cookie on the current domain
    await driver.manage().addCookie({ name: 'foo', value: 'bar' });

    // Get cookie details with named cookie 'foo'
    await driver.manage().getCookie('foo').then(function(cookie) {
      console.log('cookie details => ', cookie);
    });
  });

  it('Read all cookies', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // Add few cookies
    await driver.manage().addCookie({ name: 'test1', value: 'cookie1' });
    await driver.manage().addCookie({ name: 'test2', value: 'cookie2' });

    // Get all Available cookies
    await driver.manage().getCookies().then(function(cookies) {
      console.log('cookie details => ', cookies);
    });
  });

  it('Delete a cookie', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // Add few cookies
    await driver.manage().addCookie({ name: 'test1', value: 'cookie1' });
    await driver.manage().addCookie({ name: 'test2', value: 'cookie2' });

    // Delete a cookie with name 'test1'
    await driver.manage().deleteCookie('test1');

    // Get all Available cookies
    await driver.manage().getCookies().then(function(cookies) {
      console.log('cookie details => ', cookies);
    });
  });

  it('Delete all cookies', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // Add few cookies
    await driver.manage().addCookie({ name: 'test1', value: 'cookie1' });
    await driver.manage().addCookie({ name: 'test2', value: 'cookie2' });

    // Delete all cookies
    await driver.manage().deleteAllCookies();
  });
});
import org.openqa.selenium.Cookie
import org.openqa.selenium.chrome.ChromeDriver

fun main() {
    val driver = ChromeDriver()
    try {
        driver.get("https://example.com")
        driver.manage().addCookie(Cookie("test1", "cookie1"))
        val cookie1 = Cookie("test2", "cookie2")
        driver.manage().addCookie(cookie1)

        // delete a cookie with name 'test1'
        driver.manage().deleteCookieNamed("test1")
        
        // delete cookie by passing cookie object of current browsing context.
        driver.manage().deleteCookie(cookie1)
    } finally {
        driver.quit()
    }
}  
  

Delete All Cookies

Exclui todos os cookies do contexto de navegação atual.

	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        // Add cookies into current browser context
	        driver.manage().addCookie(new Cookie("test1", "cookie1"));
	        driver.manage().addCookie(new Cookie("test2", "cookie2"));
	        // Delete All cookies
	        driver.manage().deleteAllCookies();
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Set;

public class CookiesTest {

	WebDriver driver = new ChromeDriver();
	@Test
	  public void addCookie() {
	      driver.get("https://www.selenium.dev/selenium/web/blank.html");
	      // Add cookie into current browser context
	      driver.manage().addCookie(new Cookie("key", "value"));
	      driver.quit();
	}
	    @Test
	    public void getNamedCookie() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        // Add cookie into current browser context
	        driver.manage().addCookie(new Cookie("foo", "bar"));
	        // Get cookie details with named cookie 'foo'
	        Cookie cookie = driver.manage().getCookieNamed("foo");
	        Assertions.assertEquals(cookie.getValue(), "bar");
	     
	        driver.quit();
	      }
	  

	    @Test
	    public void getAllCookies() {
	      
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        // Add cookies into current browser context
	        driver.manage().addCookie(new Cookie("test1", "cookie1"));
	        driver.manage().addCookie(new Cookie("test2", "cookie2"));
	        // Get cookies
	        Set<Cookie> cookies = driver.manage().getCookies();
	         for (Cookie cookie : cookies) {
	            if (cookie.getName().equals("test1")) {
	                Assertions.assertEquals(cookie.getValue(), "cookie1");
	            }

	            if (cookie.getName().equals("test2")) {
	                Assertions.assertEquals(cookie.getValue(), "cookie2");
	            }
	         }
	         driver.quit();
	      }
	   

	    @Test
	    public void deleteCookieNamed() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        driver.manage().addCookie(new Cookie("test1", "cookie1"));
	        // delete cookie named
	        driver.manage().deleteCookieNamed("test1");
	        driver.quit();
	    }

	    @Test
	    public void deleteCookieObject() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        Cookie cookie = new Cookie("test2", "cookie2");
	        driver.manage().addCookie(cookie);
	        /*
	        Selenium Java bindings also provides a way to delete
	        cookie by passing cookie object of current browsing context
	        */
	        driver.manage().deleteCookie(cookie);
	      
	        driver.quit();
	      }
	  

	    @Test
	    public void deleteAllCookies() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        // Add cookies into current browser context
	        driver.manage().addCookie(new Cookie("test1", "cookie1"));
	        driver.manage().addCookie(new Cookie("test2", "cookie2"));
	        // Delete All cookies
	        driver.manage().deleteAllCookies();
	     
	        driver.quit();
	      }

		  @Test
		  public void sameSiteCookie() {
		    driver.get("http://www.example.com");

     	    Cookie cookie = new Cookie.Builder("key", "value").sameSite("Strict").build();
            Cookie cookie1 = new Cookie.Builder("key", "value").sameSite("Lax").build();

            driver.manage().addCookie(cookie);
            driver.manage().addCookie(cookie1);

            System.out.println(cookie.getSameSite());
            System.out.println(cookie1.getSameSite());

			driver.quit();
		  }
}
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Delete all cookies
    driver.delete_all_cookies()
Show full example
from selenium import webdriver


def add_cookie():
    driver = webdriver.Chrome()
    driver.get("http://www.example.com")

    # Adds the cookie into current browser context
    driver.add_cookie({"name": "key", "value": "value"})


def get_named_cookie():
    driver = webdriver.Chrome()
    driver.get("http://www.example.com")

    # Adds the cookie into current browser context
    driver.add_cookie({"name": "foo", "value": "bar"})

    # Get cookie details with named cookie 'foo'
    print(driver.get_cookie("foo"))


def get_all_cookies():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Get all available cookies
    print(driver.get_cookies())

def delete_cookie():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Delete cookie with name 'test1'
    driver.delete_cookie("test1")


def delete_all_cookies():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Delete all cookies
    driver.delete_all_cookies()


def same_side_cookie_attr():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    # Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'
    driver.add_cookie({"name": "foo", "value": "value", "sameSite": "Strict"})
    driver.add_cookie({"name": "foo1", "value": "value", "sameSite": "Lax"})

    cookie1 = driver.get_cookie("foo")
    cookie2 = driver.get_cookie("foo1")

    print(cookie1)
    print(cookie2)
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         // Add cookies into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("test1", "cookie1"));
         driver.Manage().Cookies.AddCookie(new Cookie("test2", "cookie2"));
         // Delete All cookies
         driver.Manage().Cookies.DeleteAllCookies();
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocs.Interactions{

[TestClass]
public class CookiesTest{
     
    WebDriver driver = new ChromeDriver();

     [TestMethod]
      public void addCookie(){
         driver.Url="https://www.selenium.dev/selenium/web/blank.html";
         // Add cookie into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("key", "value"));
         driver.Quit();
     }
     
     [TestMethod]
     public void getNamedCookie(){  
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         // Add cookie into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("foo", "bar"));
         // Get cookie details with named cookie 'foo'
         Cookie cookie = driver.Manage().Cookies.GetCookieNamed("foo");
         Assert.AreEqual(cookie.Value, "bar");
         driver.Quit();
     }

     [TestMethod]
     public void getAllCookies(){
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         // Add cookies into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("test1", "cookie1"));
         driver.Manage().Cookies.AddCookie(new Cookie("test2", "cookie2"));
         // Get cookies
         var cookies = driver.Manage().Cookies.AllCookies;
         foreach (var cookie in cookies){
             if (cookie.Name.Equals("test1")){
                 Assert.AreEqual("cookie1", cookie.Value);
             }
             if (cookie.Name.Equals("test2")){
                 Assert.AreEqual("cookie2", cookie.Value);
             }
         }
         driver.Quit();
     }
     
     [TestMethod]
     public void deleteCookieNamed(){
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         driver.Manage().Cookies.AddCookie(new Cookie("test1", "cookie1"));
         // delete cookie named
         driver.Manage().Cookies.DeleteCookieNamed("test1");
         driver.Quit();
     }

     [TestMethod]
     public void deleteCookieObject(){
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         Cookie cookie = new Cookie("test2", "cookie2");
         driver.Manage().Cookies.AddCookie(cookie);
         /*
      Selenium CSharp bindings also provides a way to delete
      cookie by passing cookie object of current browsing context
      */
         driver.Manage().Cookies.DeleteCookie(cookie);
         driver.Quit();
     }
     
     [TestMethod]
     public void deleteAllCookies(){
         driver.Url = "https://www.selenium.dev/selenium/web/blank.html";
         // Add cookies into current browser context
         driver.Manage().Cookies.AddCookie(new Cookie("test1", "cookie1"));
         driver.Manage().Cookies.AddCookie(new Cookie("test2", "cookie2"));
         // Delete All cookies
         driver.Manage().Cookies.DeleteAllCookies();
         driver.Quit();
     }
    }
}
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :chrome

begin
  driver.get 'https://www.example.com'
  driver.manage.add_cookie(name: "test1", value: "cookie1")
  driver.manage.add_cookie(name: "test2", value: "cookie2")

  # deletes all cookies
  driver.manage.delete_all_cookies
ensure
  driver.quit
end
  
    await driver.manage().addCookie({ name: 'test2', value: 'cookie2' });
Show full example

const {Browser, Builder} = require("selenium-webdriver");


describe('Cookies', function() {
  let driver;

  before(async function() {
    driver = new Builder()
      .forBrowser(Browser.CHROME)
      .build();
  });

  after(async () => await driver.quit());

  it('Create a cookie', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // set a cookie on the current domain
    await driver.manage().addCookie({ name: 'key', value: 'value' });
  });

  it('Create cookies with sameSite', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'
    await driver.manage().addCookie({ name: 'key', value: 'value', sameSite: 'Strict' });
    await driver.manage().addCookie({ name: 'key', value: 'value', sameSite: 'Lax' });
  });

  it('Read cookie', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // set a cookie on the current domain
    await driver.manage().addCookie({ name: 'foo', value: 'bar' });

    // Get cookie details with named cookie 'foo'
    await driver.manage().getCookie('foo').then(function(cookie) {
      console.log('cookie details => ', cookie);
    });
  });

  it('Read all cookies', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // Add few cookies
    await driver.manage().addCookie({ name: 'test1', value: 'cookie1' });
    await driver.manage().addCookie({ name: 'test2', value: 'cookie2' });

    // Get all Available cookies
    await driver.manage().getCookies().then(function(cookies) {
      console.log('cookie details => ', cookies);
    });
  });

  it('Delete a cookie', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // Add few cookies
    await driver.manage().addCookie({ name: 'test1', value: 'cookie1' });
    await driver.manage().addCookie({ name: 'test2', value: 'cookie2' });

    // Delete a cookie with name 'test1'
    await driver.manage().deleteCookie('test1');

    // Get all Available cookies
    await driver.manage().getCookies().then(function(cookies) {
      console.log('cookie details => ', cookies);
    });
  });

  it('Delete all cookies', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // Add few cookies
    await driver.manage().addCookie({ name: 'test1', value: 'cookie1' });
    await driver.manage().addCookie({ name: 'test2', value: 'cookie2' });

    // Delete all cookies
    await driver.manage().deleteAllCookies();
  });
});
import org.openqa.selenium.Cookie
import org.openqa.selenium.chrome.ChromeDriver

fun main() {
    val driver = ChromeDriver()
    try {
        driver.get("https://example.com")
        driver.manage().addCookie(Cookie("test1", "cookie1"))
        driver.manage().addCookie(Cookie("test2", "cookie2"))

        // deletes all cookies
        driver.manage().deleteAllCookies()
    } finally {
        driver.quit()
    }
}  
  

Permite que um usuário instrua os navegadores a controlar se os cookies são enviados junto com a solicitação iniciada por sites de terceiros. É usado para evitar ataques CSRF (Cross-Site Request Forgery).

O atributo de cookie Same-Site aceita dois parâmetros como instruções

Strict:

Quando o atributo sameSite é definido como Strict, o cookie não será enviado junto com solicitações iniciadas por sites de terceiros.

Lax:

Quando você define um atributo cookie sameSite como Lax, o cookie será enviado junto com uma solicitação GET iniciada por um site de terceiros.

Nota: a partir de agora, esse recurso está disponível no Chrome (versão 80+), Firefox (versão 79+) e funciona com Selenium 4 e versões posteriores.

		    driver.get("http://www.example.com");

     	    Cookie cookie = new Cookie.Builder("key", "value").sameSite("Strict").build();
            Cookie cookie1 = new Cookie.Builder("key", "value").sameSite("Lax").build();

            driver.manage().addCookie(cookie);
            driver.manage().addCookie(cookie1);

            System.out.println(cookie.getSameSite());
            System.out.println(cookie1.getSameSite());
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Set;

public class CookiesTest {

	WebDriver driver = new ChromeDriver();
	@Test
	  public void addCookie() {
	      driver.get("https://www.selenium.dev/selenium/web/blank.html");
	      // Add cookie into current browser context
	      driver.manage().addCookie(new Cookie("key", "value"));
	      driver.quit();
	}
	    @Test
	    public void getNamedCookie() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        // Add cookie into current browser context
	        driver.manage().addCookie(new Cookie("foo", "bar"));
	        // Get cookie details with named cookie 'foo'
	        Cookie cookie = driver.manage().getCookieNamed("foo");
	        Assertions.assertEquals(cookie.getValue(), "bar");
	     
	        driver.quit();
	      }
	  

	    @Test
	    public void getAllCookies() {
	      
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        // Add cookies into current browser context
	        driver.manage().addCookie(new Cookie("test1", "cookie1"));
	        driver.manage().addCookie(new Cookie("test2", "cookie2"));
	        // Get cookies
	        Set<Cookie> cookies = driver.manage().getCookies();
	         for (Cookie cookie : cookies) {
	            if (cookie.getName().equals("test1")) {
	                Assertions.assertEquals(cookie.getValue(), "cookie1");
	            }

	            if (cookie.getName().equals("test2")) {
	                Assertions.assertEquals(cookie.getValue(), "cookie2");
	            }
	         }
	         driver.quit();
	      }
	   

	    @Test
	    public void deleteCookieNamed() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        driver.manage().addCookie(new Cookie("test1", "cookie1"));
	        // delete cookie named
	        driver.manage().deleteCookieNamed("test1");
	        driver.quit();
	    }

	    @Test
	    public void deleteCookieObject() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        Cookie cookie = new Cookie("test2", "cookie2");
	        driver.manage().addCookie(cookie);
	        /*
	        Selenium Java bindings also provides a way to delete
	        cookie by passing cookie object of current browsing context
	        */
	        driver.manage().deleteCookie(cookie);
	      
	        driver.quit();
	      }
	  

	    @Test
	    public void deleteAllCookies() {
	     
	        driver.get("https://www.selenium.dev/selenium/web/blank.html");
	        // Add cookies into current browser context
	        driver.manage().addCookie(new Cookie("test1", "cookie1"));
	        driver.manage().addCookie(new Cookie("test2", "cookie2"));
	        // Delete All cookies
	        driver.manage().deleteAllCookies();
	     
	        driver.quit();
	      }

		  @Test
		  public void sameSiteCookie() {
		    driver.get("http://www.example.com");

     	    Cookie cookie = new Cookie.Builder("key", "value").sameSite("Strict").build();
            Cookie cookie1 = new Cookie.Builder("key", "value").sameSite("Lax").build();

            driver.manage().addCookie(cookie);
            driver.manage().addCookie(cookie1);

            System.out.println(cookie.getSameSite());
            System.out.println(cookie1.getSameSite());

			driver.quit();
		  }
}
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    # Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'
    driver.add_cookie({"name": "foo", "value": "value", "sameSite": "Strict"})
    driver.add_cookie({"name": "foo1", "value": "value", "sameSite": "Lax"})

    cookie1 = driver.get_cookie("foo")
    cookie2 = driver.get_cookie("foo1")

    print(cookie1)
    print(cookie2)
Show full example
from selenium import webdriver


def add_cookie():
    driver = webdriver.Chrome()
    driver.get("http://www.example.com")

    # Adds the cookie into current browser context
    driver.add_cookie({"name": "key", "value": "value"})


def get_named_cookie():
    driver = webdriver.Chrome()
    driver.get("http://www.example.com")

    # Adds the cookie into current browser context
    driver.add_cookie({"name": "foo", "value": "bar"})

    # Get cookie details with named cookie 'foo'
    print(driver.get_cookie("foo"))


def get_all_cookies():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Get all available cookies
    print(driver.get_cookies())

def delete_cookie():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Delete cookie with name 'test1'
    driver.delete_cookie("test1")


def delete_all_cookies():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    driver.add_cookie({"name": "test1", "value": "cookie1"})
    driver.add_cookie({"name": "test2", "value": "cookie2"})

    # Delete all cookies
    driver.delete_all_cookies()


def same_side_cookie_attr():
    driver = webdriver.Chrome()

    driver.get("http://www.example.com")

    # Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'
    driver.add_cookie({"name": "foo", "value": "value", "sameSite": "Strict"})
    driver.add_cookie({"name": "foo1", "value": "value", "sameSite": "Lax"})

    cookie1 = driver.get_cookie("foo")
    cookie2 = driver.get_cookie("foo1")

    print(cookie1)
    print(cookie2)
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SameSiteCookie {
  class SameSiteCookie {
    static void Main(string[] args) {
      IWebDriver driver = new ChromeDriver();
      try {
        driver.Navigate().GoToUrl("http://www.example.com");

        var cookie1Dictionary = new System.Collections.Generic.Dictionary<string, object>() {
          { "name", "test1" }, { "value", "cookie1" }, { "sameSite", "Strict" } };
        var cookie1 = Cookie.FromDictionary(cookie1Dictionary);

        var cookie2Dictionary = new System.Collections.Generic.Dictionary<string, object>() {
          { "name", "test2" }, { "value", "cookie2" }, { "sameSite", "Lax" } };
        var cookie2 = Cookie.FromDictionary(cookie2Dictionary);

        driver.Manage().Cookies.AddCookie(cookie1);
        driver.Manage().Cookies.AddCookie(cookie2);

        System.Console.WriteLine(cookie1.SameSite);
        System.Console.WriteLine(cookie2.SameSite);
      } finally {
        driver.Quit();
      }
    }
  }
}
  
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :chrome

begin
  driver.get 'https://www.example.com'
  # Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'
  driver.manage.add_cookie(name: "foo", value: "bar", same_site: "Strict")
  driver.manage.add_cookie(name: "foo1", value: "bar", same_site: "Lax")
  puts driver.manage.cookie_named('foo')
  puts driver.manage.cookie_named('foo1')
ensure
  driver.quit
end
  
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'
Show full example

const {Browser, Builder} = require("selenium-webdriver");


describe('Cookies', function() {
  let driver;

  before(async function() {
    driver = new Builder()
      .forBrowser(Browser.CHROME)
      .build();
  });

  after(async () => await driver.quit());

  it('Create a cookie', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // set a cookie on the current domain
    await driver.manage().addCookie({ name: 'key', value: 'value' });
  });

  it('Create cookies with sameSite', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // set a cookie on the current domain with sameSite 'Strict' (or) 'Lax'
    await driver.manage().addCookie({ name: 'key', value: 'value', sameSite: 'Strict' });
    await driver.manage().addCookie({ name: 'key', value: 'value', sameSite: 'Lax' });
  });

  it('Read cookie', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // set a cookie on the current domain
    await driver.manage().addCookie({ name: 'foo', value: 'bar' });

    // Get cookie details with named cookie 'foo'
    await driver.manage().getCookie('foo').then(function(cookie) {
      console.log('cookie details => ', cookie);
    });
  });

  it('Read all cookies', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // Add few cookies
    await driver.manage().addCookie({ name: 'test1', value: 'cookie1' });
    await driver.manage().addCookie({ name: 'test2', value: 'cookie2' });

    // Get all Available cookies
    await driver.manage().getCookies().then(function(cookies) {
      console.log('cookie details => ', cookies);
    });
  });

  it('Delete a cookie', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // Add few cookies
    await driver.manage().addCookie({ name: 'test1', value: 'cookie1' });
    await driver.manage().addCookie({ name: 'test2', value: 'cookie2' });

    // Delete a cookie with name 'test1'
    await driver.manage().deleteCookie('test1');

    // Get all Available cookies
    await driver.manage().getCookies().then(function(cookies) {
      console.log('cookie details => ', cookies);
    });
  });

  it('Delete all cookies', async function() {
    await driver.get('https://www.selenium.dev/selenium/web/blank.html');

    // Add few cookies
    await driver.manage().addCookie({ name: 'test1', value: 'cookie1' });
    await driver.manage().addCookie({ name: 'test2', value: 'cookie2' });

    // Delete all cookies
    await driver.manage().deleteAllCookies();
  });
});
import org.openqa.selenium.Cookie
import org.openqa.selenium.chrome.ChromeDriver

fun main() {
    val driver = ChromeDriver()
    try {
        driver.get("http://www.example.com")
        val cookie = Cookie.Builder("key", "value").sameSite("Strict").build()
        val cookie1 = Cookie.Builder("key", "value").sameSite("Lax").build()
        driver.manage().addCookie(cookie)
        driver.manage().addCookie(cookie1)
        println(cookie.getSameSite())
        println(cookie1.getSameSite())
    } finally {
        driver.quit()
    }
}
  

4 - Working with IFrames and frames

Frames são um meio obsoleto de construir um layout de site a partir de vários documentos no mesmo domínio. É improvável que você trabalhe com eles a menos que você esteja trabalhando com um webapp pré-HTML5. Iframes permitem a inserção de um documento de um domínio totalmente diferente, e são ainda comumente usado.

Se você precisa trabalhar com frames ou iframes, o WebDriver permite que você trabalhe com eles da mesma maneira. Considere um botão dentro de um iframe. Se inspecionarmos o elemento usando as ferramentas de desenvolvimento do navegador, podemos ver o seguinte:

<div id="modal">
  <iframe id="buttonframe" name="myframe"  src="https://seleniumhq.github.io">
   <button>Click here</button>
 </iframe>
</div>

Se não fosse pelo iframe, esperaríamos clicar no botão usando algo como:

//This won't work
driver.findElement(By.tagName("button")).click();
  
    # This Wont work
driver.find_element(By.TAG_NAME, 'button').click()
  
//This won't work
driver.FindElement(By.TagName("button")).Click();
  
    # This won't work
driver.find_element(:tag_name,'button').click
  
// This won't work
await driver.findElement(By.css('button')).click();
  
//This won't work
driver.findElement(By.tagName("button")).click()
  

No entanto, se não houver botões fora do iframe, você pode em vez disso, obter um erro no such element. Isso acontece porque o Selenium é ciente apenas dos elementos no documento de nível superior. Para interagir com o botão, precisamos primeiro mudar para o quadro, de forma semelhante a como alternamos janelas. WebDriver oferece três maneiras de mudar para um frame.

Usando um WebElement

Alternar usando um WebElement é a opção mais flexível. Você pode encontrar o quadro usando seu seletor preferido e mudar para ele.

         //switch To IFrame using Web Element
         WebElement iframe = driver.findElement(By.id("iframe1"));
         //Switch to the frame
         driver.switchTo().frame(iframe);
         assertEquals(true, driver.getPageSource().contains("We Leave From Here"));
         //Now we can type text into email field
         WebElement emailE = driver.findElement(By.id("email"));
         emailE.sendKeys("admin@selenium.dev");
         emailE.clear();
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package dev.selenium.interactions;

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

public class FramesTest{

    @Test
    public void informationWithElements() {
    	
    	 WebDriver driver = new ChromeDriver();
         driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
        
         // Navigate to Url
         driver.get("https://www.selenium.dev/selenium/web/iframes.html");
        
         
         //switch To IFrame using Web Element
         WebElement iframe = driver.findElement(By.id("iframe1"));
         //Switch to the frame
         driver.switchTo().frame(iframe);
         assertEquals(true, driver.getPageSource().contains("We Leave From Here"));
         //Now we can type text into email field
         WebElement emailE = driver.findElement(By.id("email"));
         emailE.sendKeys("admin@selenium.dev");
         emailE.clear();
         driver.switchTo().defaultContent();
       
         
         //switch To IFrame using name or id
         driver.findElement(By.name("iframe1-name"));
         //Switch to the frame
         driver.switchTo().frame(iframe);
         assertEquals(true, driver.getPageSource().contains("We Leave From Here"));
         WebElement email = driver.findElement(By.id("email"));
         //Now we can type text into email field
         email.sendKeys("admin@selenium.dev");
         email.clear();
         driver.switchTo().defaultContent();
     
         
         //switch To IFrame using index
         driver.switchTo().frame(0);
         assertEquals(true, driver.getPageSource().contains("We Leave From Here"));
         
         //leave frame
         driver.switchTo().defaultContent();
         assertEquals(true, driver.getPageSource().contains("This page has iframes"));
         
         //quit the browser
         driver.quit();
    }

}
# --- Switch to iframe using WebElement ---
iframe = driver.find_element(By.ID, "iframe1")
driver.switch_to.frame(iframe)
assert "We Leave From Here" in driver.page_source

email_element = driver.find_element(By.ID, "email")
email_element.send_keys("admin@selenium.dev")
email_element.clear()
driver.switch_to.default_content()
Show full example
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

from selenium import webdriver
from selenium.webdriver.common.by import By

#set chrome and launch web page
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/iframes.html")

# --- Switch to iframe using WebElement ---
iframe = driver.find_element(By.ID, "iframe1")
driver.switch_to.frame(iframe)
assert "We Leave From Here" in driver.page_source

email_element = driver.find_element(By.ID, "email")
email_element.send_keys("admin@selenium.dev")
email_element.clear()
driver.switch_to.default_content()

# --- Switch to iframe using name or ID ---
iframe1=driver.find_element(By.NAME, "iframe1-name")  # (This line doesn't switch, just locates)
driver.switch_to.frame(iframe)
assert "We Leave From Here" in driver.page_source

email = driver.find_element(By.ID, "email")
email.send_keys("admin@selenium.dev")
email.clear()
driver.switch_to.default_content()

# --- Switch to iframe using index ---
driver.switch_to.frame(0)
assert "We Leave From Here" in driver.page_source

# --- Final page content check ---
driver.switch_to.default_content()
assert "This page has iframes" in driver.page_source

#quit the driver
driver.quit()

#demo code for conference
            //switch To IFrame using Web Element
            IWebElement iframe = driver.FindElement(By.Id("iframe1"));
            //Switch to the frame
            driver.SwitchTo().Frame(iframe);
            Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));
            //Now we can type text into email field
            IWebElement emailE = driver.FindElement(By.Id("email"));
            emailE.SendKeys("admin@selenium.dev");
            emailE.Clear();
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Collections.Generic;

namespace SeleniumDocs.Interactions
{
  [TestClass]
    public class FramesTest
    {
        [TestMethod]
        public void TestFrames()
        {
            WebDriver driver = new ChromeDriver();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);

            // Navigate to Url
            driver.Url= "https://www.selenium.dev/selenium/web/iframes.html";
            //switch To IFrame using Web Element
            IWebElement iframe = driver.FindElement(By.Id("iframe1"));
            //Switch to the frame
            driver.SwitchTo().Frame(iframe);
            Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));
            //Now we can type text into email field
            IWebElement emailE = driver.FindElement(By.Id("email"));
            emailE.SendKeys("admin@selenium.dev");
            emailE.Clear();
            driver.SwitchTo().DefaultContent();


            //switch To IFrame using name or id
            driver.FindElement(By.Name("iframe1-name"));
            //Switch to the frame
            driver.SwitchTo().Frame(iframe);
            Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));
            IWebElement email = driver.FindElement(By.Id("email"));
            //Now we can type text into email field
            email.SendKeys("admin@selenium.dev");
            email.Clear();
            driver.SwitchTo().DefaultContent();


            //switch To IFrame using index
            driver.SwitchTo().Frame(0);
            Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));

            //leave frame
            driver.SwitchTo().DefaultContent();
            Assert.AreEqual(true, driver.PageSource.Contains("This page has iframes"));

            //quit the browser
            driver.Quit();
        }
    }
}
    # Store iframe web element
iframe = driver.find_element(:css,'#modal > iframe')

    # Switch to the frame
driver.switch_to.frame iframe

    # Now, Click on the button
driver.find_element(:tag_name,'button').click
  
// Store the web element
const iframe = driver.findElement(By.css('#modal > iframe'));

// Switch to the frame
await driver.switchTo().frame(iframe);

// Now we can click the button
await driver.findElement(By.css('button')).click();
  
//Store the web element
val iframe = driver.findElement(By.cssSelector("#modal>iframe"))

//Switch to the frame
driver.switchTo().frame(iframe)

//Now we can click the button
driver.findElement(By.tagName("button")).click()
  

Usando um name ou ID

Se o seu frame ou iframe tiver um atributo id ou name, ele pode ser usado alternativamente. Se o name ou ID não for exclusivo na página, o primeiro encontrado será utilizado.

         //switch To IFrame using name or id
         driver.findElement(By.name("iframe1-name"));
         //Switch to the frame
         driver.switchTo().frame(iframe);
         assertEquals(true, driver.getPageSource().contains("We Leave From Here"));
         WebElement email = driver.findElement(By.id("email"));
         //Now we can type text into email field
         email.sendKeys("admin@selenium.dev");
         email.clear();
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package dev.selenium.interactions;

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

public class FramesTest{

    @Test
    public void informationWithElements() {
    	
    	 WebDriver driver = new ChromeDriver();
         driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
        
         // Navigate to Url
         driver.get("https://www.selenium.dev/selenium/web/iframes.html");
        
         
         //switch To IFrame using Web Element
         WebElement iframe = driver.findElement(By.id("iframe1"));
         //Switch to the frame
         driver.switchTo().frame(iframe);
         assertEquals(true, driver.getPageSource().contains("We Leave From Here"));
         //Now we can type text into email field
         WebElement emailE = driver.findElement(By.id("email"));
         emailE.sendKeys("admin@selenium.dev");
         emailE.clear();
         driver.switchTo().defaultContent();
       
         
         //switch To IFrame using name or id
         driver.findElement(By.name("iframe1-name"));
         //Switch to the frame
         driver.switchTo().frame(iframe);
         assertEquals(true, driver.getPageSource().contains("We Leave From Here"));
         WebElement email = driver.findElement(By.id("email"));
         //Now we can type text into email field
         email.sendKeys("admin@selenium.dev");
         email.clear();
         driver.switchTo().defaultContent();
     
         
         //switch To IFrame using index
         driver.switchTo().frame(0);
         assertEquals(true, driver.getPageSource().contains("We Leave From Here"));
         
         //leave frame
         driver.switchTo().defaultContent();
         assertEquals(true, driver.getPageSource().contains("This page has iframes"));
         
         //quit the browser
         driver.quit();
    }

}
# --- Switch to iframe using name or ID ---
iframe1=driver.find_element(By.NAME, "iframe1-name")  # (This line doesn't switch, just locates)
driver.switch_to.frame(iframe)
assert "We Leave From Here" in driver.page_source

email = driver.find_element(By.ID, "email")
email.send_keys("admin@selenium.dev")
email.clear()
driver.switch_to.default_content()
Show full example
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

from selenium import webdriver
from selenium.webdriver.common.by import By

#set chrome and launch web page
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/iframes.html")

# --- Switch to iframe using WebElement ---
iframe = driver.find_element(By.ID, "iframe1")
driver.switch_to.frame(iframe)
assert "We Leave From Here" in driver.page_source

email_element = driver.find_element(By.ID, "email")
email_element.send_keys("admin@selenium.dev")
email_element.clear()
driver.switch_to.default_content()

# --- Switch to iframe using name or ID ---
iframe1=driver.find_element(By.NAME, "iframe1-name")  # (This line doesn't switch, just locates)
driver.switch_to.frame(iframe)
assert "We Leave From Here" in driver.page_source

email = driver.find_element(By.ID, "email")
email.send_keys("admin@selenium.dev")
email.clear()
driver.switch_to.default_content()

# --- Switch to iframe using index ---
driver.switch_to.frame(0)
assert "We Leave From Here" in driver.page_source

# --- Final page content check ---
driver.switch_to.default_content()
assert "This page has iframes" in driver.page_source

#quit the driver
driver.quit()

#demo code for conference
            //switch To IFrame using name or id
            driver.FindElement(By.Name("iframe1-name"));
            //Switch to the frame
            driver.SwitchTo().Frame(iframe);
            Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));
            IWebElement email = driver.FindElement(By.Id("email"));
            //Now we can type text into email field
            email.SendKeys("admin@selenium.dev");
            email.Clear();
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Collections.Generic;

namespace SeleniumDocs.Interactions
{
  [TestClass]
    public class FramesTest
    {
        [TestMethod]
        public void TestFrames()
        {
            WebDriver driver = new ChromeDriver();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);

            // Navigate to Url
            driver.Url= "https://www.selenium.dev/selenium/web/iframes.html";
            //switch To IFrame using Web Element
            IWebElement iframe = driver.FindElement(By.Id("iframe1"));
            //Switch to the frame
            driver.SwitchTo().Frame(iframe);
            Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));
            //Now we can type text into email field
            IWebElement emailE = driver.FindElement(By.Id("email"));
            emailE.SendKeys("admin@selenium.dev");
            emailE.Clear();
            driver.SwitchTo().DefaultContent();


            //switch To IFrame using name or id
            driver.FindElement(By.Name("iframe1-name"));
            //Switch to the frame
            driver.SwitchTo().Frame(iframe);
            Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));
            IWebElement email = driver.FindElement(By.Id("email"));
            //Now we can type text into email field
            email.SendKeys("admin@selenium.dev");
            email.Clear();
            driver.SwitchTo().DefaultContent();


            //switch To IFrame using index
            driver.SwitchTo().Frame(0);
            Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));

            //leave frame
            driver.SwitchTo().DefaultContent();
            Assert.AreEqual(true, driver.PageSource.Contains("This page has iframes"));

            //quit the browser
            driver.Quit();
        }
    }
}
    # Switch by ID
driver.switch_to.frame 'buttonframe'

    # Now, Click on the button
driver.find_element(:tag_name,'button').click
  
// Using the ID
await driver.switchTo().frame('buttonframe');

// Or using the name instead
await driver.switchTo().frame('myframe');

// Now we can click the button
await driver.findElement(By.css('button')).click();
  
//Using the ID
driver.switchTo().frame("buttonframe")

//Or using the name instead
driver.switchTo().frame("myframe")

//Now we can click the button
driver.findElement(By.tagName("button")).click()
  

Usando um índice

Também é possível usar o índice do frame, podendo ser consultado usando window.frames em JavaScript.

         //switch To IFrame using index
         driver.switchTo().frame(0);
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package dev.selenium.interactions;

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

public class FramesTest{

    @Test
    public void informationWithElements() {
    	
    	 WebDriver driver = new ChromeDriver();
         driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
        
         // Navigate to Url
         driver.get("https://www.selenium.dev/selenium/web/iframes.html");
        
         
         //switch To IFrame using Web Element
         WebElement iframe = driver.findElement(By.id("iframe1"));
         //Switch to the frame
         driver.switchTo().frame(iframe);
         assertEquals(true, driver.getPageSource().contains("We Leave From Here"));
         //Now we can type text into email field
         WebElement emailE = driver.findElement(By.id("email"));
         emailE.sendKeys("admin@selenium.dev");
         emailE.clear();
         driver.switchTo().defaultContent();
       
         
         //switch To IFrame using name or id
         driver.findElement(By.name("iframe1-name"));
         //Switch to the frame
         driver.switchTo().frame(iframe);
         assertEquals(true, driver.getPageSource().contains("We Leave From Here"));
         WebElement email = driver.findElement(By.id("email"));
         //Now we can type text into email field
         email.sendKeys("admin@selenium.dev");
         email.clear();
         driver.switchTo().defaultContent();
     
         
         //switch To IFrame using index
         driver.switchTo().frame(0);
         assertEquals(true, driver.getPageSource().contains("We Leave From Here"));
         
         //leave frame
         driver.switchTo().defaultContent();
         assertEquals(true, driver.getPageSource().contains("This page has iframes"));
         
         //quit the browser
         driver.quit();
    }

}
driver.switch_to.frame(0)
assert "We Leave From Here" in driver.page_source
Show full example
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

from selenium import webdriver
from selenium.webdriver.common.by import By

#set chrome and launch web page
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/iframes.html")

# --- Switch to iframe using WebElement ---
iframe = driver.find_element(By.ID, "iframe1")
driver.switch_to.frame(iframe)
assert "We Leave From Here" in driver.page_source

email_element = driver.find_element(By.ID, "email")
email_element.send_keys("admin@selenium.dev")
email_element.clear()
driver.switch_to.default_content()

# --- Switch to iframe using name or ID ---
iframe1=driver.find_element(By.NAME, "iframe1-name")  # (This line doesn't switch, just locates)
driver.switch_to.frame(iframe)
assert "We Leave From Here" in driver.page_source

email = driver.find_element(By.ID, "email")
email.send_keys("admin@selenium.dev")
email.clear()
driver.switch_to.default_content()

# --- Switch to iframe using index ---
driver.switch_to.frame(0)
assert "We Leave From Here" in driver.page_source

# --- Final page content check ---
driver.switch_to.default_content()
assert "This page has iframes" in driver.page_source

#quit the driver
driver.quit()

#demo code for conference
# Switch to the second frame
driver.switch_to.frame(1)
            //switch To IFrame using index
            driver.SwitchTo().Frame(0);
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Collections.Generic;

namespace SeleniumDocs.Interactions
{
  [TestClass]
    public class FramesTest
    {
        [TestMethod]
        public void TestFrames()
        {
            WebDriver driver = new ChromeDriver();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);

            // Navigate to Url
            driver.Url= "https://www.selenium.dev/selenium/web/iframes.html";
            //switch To IFrame using Web Element
            IWebElement iframe = driver.FindElement(By.Id("iframe1"));
            //Switch to the frame
            driver.SwitchTo().Frame(iframe);
            Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));
            //Now we can type text into email field
            IWebElement emailE = driver.FindElement(By.Id("email"));
            emailE.SendKeys("admin@selenium.dev");
            emailE.Clear();
            driver.SwitchTo().DefaultContent();


            //switch To IFrame using name or id
            driver.FindElement(By.Name("iframe1-name"));
            //Switch to the frame
            driver.SwitchTo().Frame(iframe);
            Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));
            IWebElement email = driver.FindElement(By.Id("email"));
            //Now we can type text into email field
            email.SendKeys("admin@selenium.dev");
            email.Clear();
            driver.SwitchTo().DefaultContent();


            //switch To IFrame using index
            driver.SwitchTo().Frame(0);
            Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));

            //leave frame
            driver.SwitchTo().DefaultContent();
            Assert.AreEqual(true, driver.PageSource.Contains("This page has iframes"));

            //quit the browser
            driver.Quit();
        }
    }
}
// Switches to the second frame
await driver.switchTo().frame(1);
// Switches to the second frame
driver.switchTo().frame(1)

Deixando um frame

Para deixar um iframe ou frameset, volte para o conteúdo padrão como a seguir:

         //leave frame
         driver.switchTo().defaultContent();
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package dev.selenium.interactions;

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

public class FramesTest{

    @Test
    public void informationWithElements() {
    	
    	 WebDriver driver = new ChromeDriver();
         driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
        
         // Navigate to Url
         driver.get("https://www.selenium.dev/selenium/web/iframes.html");
        
         
         //switch To IFrame using Web Element
         WebElement iframe = driver.findElement(By.id("iframe1"));
         //Switch to the frame
         driver.switchTo().frame(iframe);
         assertEquals(true, driver.getPageSource().contains("We Leave From Here"));
         //Now we can type text into email field
         WebElement emailE = driver.findElement(By.id("email"));
         emailE.sendKeys("admin@selenium.dev");
         emailE.clear();
         driver.switchTo().defaultContent();
       
         
         //switch To IFrame using name or id
         driver.findElement(By.name("iframe1-name"));
         //Switch to the frame
         driver.switchTo().frame(iframe);
         assertEquals(true, driver.getPageSource().contains("We Leave From Here"));
         WebElement email = driver.findElement(By.id("email"));
         //Now we can type text into email field
         email.sendKeys("admin@selenium.dev");
         email.clear();
         driver.switchTo().defaultContent();
     
         
         //switch To IFrame using index
         driver.switchTo().frame(0);
         assertEquals(true, driver.getPageSource().contains("We Leave From Here"));
         
         //leave frame
         driver.switchTo().defaultContent();
         assertEquals(true, driver.getPageSource().contains("This page has iframes"));
         
         //quit the browser
         driver.quit();
    }

}
driver.switch_to.default_content()
assert "This page has iframes" in driver.page_source
Show full example
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

from selenium import webdriver
from selenium.webdriver.common.by import By

#set chrome and launch web page
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/iframes.html")

# --- Switch to iframe using WebElement ---
iframe = driver.find_element(By.ID, "iframe1")
driver.switch_to.frame(iframe)
assert "We Leave From Here" in driver.page_source

email_element = driver.find_element(By.ID, "email")
email_element.send_keys("admin@selenium.dev")
email_element.clear()
driver.switch_to.default_content()

# --- Switch to iframe using name or ID ---
iframe1=driver.find_element(By.NAME, "iframe1-name")  # (This line doesn't switch, just locates)
driver.switch_to.frame(iframe)
assert "We Leave From Here" in driver.page_source

email = driver.find_element(By.ID, "email")
email.send_keys("admin@selenium.dev")
email.clear()
driver.switch_to.default_content()

# --- Switch to iframe using index ---
driver.switch_to.frame(0)
assert "We Leave From Here" in driver.page_source

# --- Final page content check ---
driver.switch_to.default_content()
assert "This page has iframes" in driver.page_source

#quit the driver
driver.quit()

#demo code for conference
            //leave frame
            driver.SwitchTo().DefaultContent();
Show full example
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.


using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Collections.Generic;

namespace SeleniumDocs.Interactions
{
  [TestClass]
    public class FramesTest
    {
        [TestMethod]
        public void TestFrames()
        {
            WebDriver driver = new ChromeDriver();
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);

            // Navigate to Url
            driver.Url= "https://www.selenium.dev/selenium/web/iframes.html";
            //switch To IFrame using Web Element
            IWebElement iframe = driver.FindElement(By.Id("iframe1"));
            //Switch to the frame
            driver.SwitchTo().Frame(iframe);
            Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));
            //Now we can type text into email field
            IWebElement emailE = driver.FindElement(By.Id("email"));
            emailE.SendKeys("admin@selenium.dev");
            emailE.Clear();
            driver.SwitchTo().DefaultContent();


            //switch To IFrame using name or id
            driver.FindElement(By.Name("iframe1-name"));
            //Switch to the frame
            driver.SwitchTo().Frame(iframe);
            Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));
            IWebElement email = driver.FindElement(By.Id("email"));
            //Now we can type text into email field
            email.SendKeys("admin@selenium.dev");
            email.Clear();
            driver.SwitchTo().DefaultContent();


            //switch To IFrame using index
            driver.SwitchTo().Frame(0);
            Assert.AreEqual(true, driver.PageSource.Contains("We Leave From Here"));

            //leave frame
            driver.SwitchTo().DefaultContent();
            Assert.AreEqual(true, driver.PageSource.Contains("This page has iframes"));

            //quit the browser
            driver.Quit();
        }
    }
}
# Return to the top level
driver.switch_to.default_content
// Return to the top level
await driver.switchTo().defaultContent();
// Return to the top level
driver.switchTo().defaultContent()

5 - Print Page

Printing a webpage is a common task, whether for sharing information or maintaining archives. Selenium simplifies this process through its PrintOptions, PrintsPage, and browsingContext classes, which provide a flexible and intuitive interface for automating the printing of web pages. These classes enable you to configure printing preferences, such as page layout, margins, and scaling, ensuring that the output meets your specific requirements.

Configuring

Orientation

Using the getOrientation() and setOrientation() methods, you can get/set the page orientation — either PORTRAIT or LANDSCAPE.

        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setOrientation(PrintOptions.Orientation.LANDSCAPE);
        PrintOptions.Orientation current_orientation = printOptions.getOrientation();
Show full example
package dev.selenium.interactions;

import org.junit.jupiter.api.Test;
import org.openqa.selenium.print.PageMargin;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.print.PageSize;
import dev.selenium.BaseChromeTest;

public class PrintOptionsTest extends BaseChromeTest {

    @Test
    public void TestOrientation() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setOrientation(PrintOptions.Orientation.LANDSCAPE);
        PrintOptions.Orientation current_orientation = printOptions.getOrientation();
    }

    @Test
    public void TestRange() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setPageRanges("1-2");
        String[] current_range = printOptions.getPageRanges();
    }

    @Test
    public void TestSize() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setPageSize(new PageSize(27.94, 21.59)); // A4 size in cm
        double currentHeight = printOptions.getPageSize().getHeight(); // use getWidth() to retrieve width
    }

    @Test
    public void TestMargins() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        PageMargin margins = new PageMargin(1.0,1.0,1.0,1.0);
        printOptions.setPageMargin(margins);
        double topMargin = margins.getTop();
        double bottomMargin = margins.getBottom();
        double leftMargin = margins.getLeft();
        double rightMargin = margins.getRight();
    }

    @Test
    public void TestScale() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setScale(.50);
        double current_scale = printOptions.getScale();
    }

    @Test
    public void TestBackground() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setBackground(true);
        boolean current_background = printOptions.getBackground();
    }

    @Test
    public void TestShrinkToFit() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setShrinkToFit(true);
        boolean current_shrink_to_fit = printOptions.getShrinkToFit();
    }
}
        public void TestOrientation()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://selenium.dev");
            PrintOptions printOptions  = new PrintOptions();
            printOptions.Orientation = PrintOrientation.Landscape;
            PrintOrientation currentOrientation = printOptions.Orientation;
        }
Show full example
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocumentation.SeleniumInteractions
{
    [TestClass]
    public class PrintOptionsTest
    {
        [TestMethod]
        public void TestOrientation()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://selenium.dev");
            PrintOptions printOptions  = new PrintOptions();
            printOptions.Orientation = PrintOrientation.Landscape;
            PrintOrientation currentOrientation = printOptions.Orientation;
        }

        [TestMethod]
        public void TestRange()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://selenium.dev");
            PrintOptions printOptions  = new PrintOptions();
            printOptions.AddPageRangeToPrint("1-3"); // add range of pages
            printOptions.AddPageToPrint(5); // add individual page
        }   

        [TestMethod]
        public void TestSize()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintOptions.PageSize currentDimensions = printOptions.PageDimensions;
        }

        [TestMethod]
        public void TestBackgrounds()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.OutputBackgroundImages = true;
            bool currentBackgrounds = printOptions.OutputBackgroundImages;
        }

        [TestMethod]
        public void TestMargins()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintOptions.Margins currentMargins = printOptions.PageMargins;
        }


        [TestMethod]
        public void TestScale()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.ScaleFactor = 0.5;
            double currentScale = printOptions.ScaleFactor;
        }

        [TestMethod]
        public void TestShrinkToFit()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.ShrinkToFit = true;
            bool currentShrinkToFit = printOptions.ShrinkToFit;
        }

        [TestMethod]
        public void PrintWithPrintsPageTest() 
        {
            WebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintDocument printedPage = driver.Print(printOptions);
            Assert.IsTrue(printedPage.AsBase64EncodedString.StartsWith("JVBER"));
        }
    }
}
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.orientation = "landscape" ## landscape or portrait
Show full example
import pytest
from selenium import webdriver
from selenium.webdriver.common.print_page_options import PrintOptions

@pytest.fixture()
def driver():
    driver = webdriver.Chrome()
    yield driver
    driver.quit()

def test_orientation(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.orientation = "landscape" ## landscape or portrait
    assert print_options.orientation == "landscape"

def test_range(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.page_ranges = ["1, 2, 3"] ## ["1", "2", "3"] or ["1-3"]
    assert print_options.page_ranges == ["1, 2, 3"]

def test_size(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.page_height = 27.94  # Use page_width to assign width
    assert print_options.page_height == 27.94

def test_margin(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.margin_top = 10
    print_options.margin_bottom = 10
    print_options.margin_left = 10
    print_options.margin_right = 10
    assert print_options.margin_top == 10
    assert print_options.margin_bottom == 10
    assert print_options.margin_left == 10
    assert print_options.margin_right == 10

def test_scale(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.scale = 0.5 ## 0.1 to 2.0
    current_scale = print_options.scale
    assert current_scale == 0.5

def test_background(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.background = True ## True or False
    assert print_options.background is True

def test_shrink_to_fit(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.shrink_to_fit = True ## True or False
    assert print_options.shrink_to_fit is True

Range

Using the getPageRanges() and setPageRanges() methods, you can get/set the range of pages to print — e.g. “2-4”.

        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setPageRanges("1-2");
        String[] current_range = printOptions.getPageRanges();
Show full example
package dev.selenium.interactions;

import org.junit.jupiter.api.Test;
import org.openqa.selenium.print.PageMargin;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.print.PageSize;
import dev.selenium.BaseChromeTest;

public class PrintOptionsTest extends BaseChromeTest {

    @Test
    public void TestOrientation() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setOrientation(PrintOptions.Orientation.LANDSCAPE);
        PrintOptions.Orientation current_orientation = printOptions.getOrientation();
    }

    @Test
    public void TestRange() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setPageRanges("1-2");
        String[] current_range = printOptions.getPageRanges();
    }

    @Test
    public void TestSize() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setPageSize(new PageSize(27.94, 21.59)); // A4 size in cm
        double currentHeight = printOptions.getPageSize().getHeight(); // use getWidth() to retrieve width
    }

    @Test
    public void TestMargins() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        PageMargin margins = new PageMargin(1.0,1.0,1.0,1.0);
        printOptions.setPageMargin(margins);
        double topMargin = margins.getTop();
        double bottomMargin = margins.getBottom();
        double leftMargin = margins.getLeft();
        double rightMargin = margins.getRight();
    }

    @Test
    public void TestScale() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setScale(.50);
        double current_scale = printOptions.getScale();
    }

    @Test
    public void TestBackground() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setBackground(true);
        boolean current_background = printOptions.getBackground();
    }

    @Test
    public void TestShrinkToFit() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setShrinkToFit(true);
        boolean current_shrink_to_fit = printOptions.getShrinkToFit();
    }
}
        public void TestRange()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://selenium.dev");
            PrintOptions printOptions  = new PrintOptions();
            printOptions.AddPageRangeToPrint("1-3"); // add range of pages
            printOptions.AddPageToPrint(5); // add individual page
        }   
Show full example
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocumentation.SeleniumInteractions
{
    [TestClass]
    public class PrintOptionsTest
    {
        [TestMethod]
        public void TestOrientation()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://selenium.dev");
            PrintOptions printOptions  = new PrintOptions();
            printOptions.Orientation = PrintOrientation.Landscape;
            PrintOrientation currentOrientation = printOptions.Orientation;
        }

        [TestMethod]
        public void TestRange()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://selenium.dev");
            PrintOptions printOptions  = new PrintOptions();
            printOptions.AddPageRangeToPrint("1-3"); // add range of pages
            printOptions.AddPageToPrint(5); // add individual page
        }   

        [TestMethod]
        public void TestSize()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintOptions.PageSize currentDimensions = printOptions.PageDimensions;
        }

        [TestMethod]
        public void TestBackgrounds()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.OutputBackgroundImages = true;
            bool currentBackgrounds = printOptions.OutputBackgroundImages;
        }

        [TestMethod]
        public void TestMargins()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintOptions.Margins currentMargins = printOptions.PageMargins;
        }


        [TestMethod]
        public void TestScale()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.ScaleFactor = 0.5;
            double currentScale = printOptions.ScaleFactor;
        }

        [TestMethod]
        public void TestShrinkToFit()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.ShrinkToFit = true;
            bool currentShrinkToFit = printOptions.ShrinkToFit;
        }

        [TestMethod]
        public void PrintWithPrintsPageTest() 
        {
            WebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintDocument printedPage = driver.Print(printOptions);
            Assert.IsTrue(printedPage.AsBase64EncodedString.StartsWith("JVBER"));
        }
    }
}
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.page_ranges = ["1, 2, 3"] ## ["1", "2", "3"] or ["1-3"]
    assert print_options.page_ranges == ["1, 2, 3"]

def test_size(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.page_height = 27.94  # Use page_width to assign width
Show full example
import pytest
from selenium import webdriver
from selenium.webdriver.common.print_page_options import PrintOptions

@pytest.fixture()
def driver():
    driver = webdriver.Chrome()
    yield driver
    driver.quit()

def test_orientation(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.orientation = "landscape" ## landscape or portrait
    assert print_options.orientation == "landscape"

def test_range(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.page_ranges = ["1, 2, 3"] ## ["1", "2", "3"] or ["1-3"]
    assert print_options.page_ranges == ["1, 2, 3"]

def test_size(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.page_height = 27.94  # Use page_width to assign width
    assert print_options.page_height == 27.94

def test_margin(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.margin_top = 10
    print_options.margin_bottom = 10
    print_options.margin_left = 10
    print_options.margin_right = 10
    assert print_options.margin_top == 10
    assert print_options.margin_bottom == 10
    assert print_options.margin_left == 10
    assert print_options.margin_right == 10

def test_scale(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.scale = 0.5 ## 0.1 to 2.0
    current_scale = print_options.scale
    assert current_scale == 0.5

def test_background(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.background = True ## True or False
    assert print_options.background is True

def test_shrink_to_fit(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.shrink_to_fit = True ## True or False
    assert print_options.shrink_to_fit is True

Size

Using the getPageSize() and setPageSize() methods, you can get/set the paper size to print — e.g. “A0”, “A6”, “Legal”, “Tabloid”, etc.

        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setPageSize(new PageSize(27.94, 21.59)); // A4 size in cm
        double currentHeight = printOptions.getPageSize().getHeight(); // use getWidth() to retrieve width
Show full example
package dev.selenium.interactions;

import org.junit.jupiter.api.Test;
import org.openqa.selenium.print.PageMargin;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.print.PageSize;
import dev.selenium.BaseChromeTest;

public class PrintOptionsTest extends BaseChromeTest {

    @Test
    public void TestOrientation() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setOrientation(PrintOptions.Orientation.LANDSCAPE);
        PrintOptions.Orientation current_orientation = printOptions.getOrientation();
    }

    @Test
    public void TestRange() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setPageRanges("1-2");
        String[] current_range = printOptions.getPageRanges();
    }

    @Test
    public void TestSize() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setPageSize(new PageSize(27.94, 21.59)); // A4 size in cm
        double currentHeight = printOptions.getPageSize().getHeight(); // use getWidth() to retrieve width
    }

    @Test
    public void TestMargins() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        PageMargin margins = new PageMargin(1.0,1.0,1.0,1.0);
        printOptions.setPageMargin(margins);
        double topMargin = margins.getTop();
        double bottomMargin = margins.getBottom();
        double leftMargin = margins.getLeft();
        double rightMargin = margins.getRight();
    }

    @Test
    public void TestScale() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setScale(.50);
        double current_scale = printOptions.getScale();
    }

    @Test
    public void TestBackground() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setBackground(true);
        boolean current_background = printOptions.getBackground();
    }

    @Test
    public void TestShrinkToFit() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setShrinkToFit(true);
        boolean current_shrink_to_fit = printOptions.getShrinkToFit();
    }
}
        public void TestSize()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintOptions.PageSize currentDimensions = printOptions.PageDimensions;
        }
Show full example
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocumentation.SeleniumInteractions
{
    [TestClass]
    public class PrintOptionsTest
    {
        [TestMethod]
        public void TestOrientation()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://selenium.dev");
            PrintOptions printOptions  = new PrintOptions();
            printOptions.Orientation = PrintOrientation.Landscape;
            PrintOrientation currentOrientation = printOptions.Orientation;
        }

        [TestMethod]
        public void TestRange()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://selenium.dev");
            PrintOptions printOptions  = new PrintOptions();
            printOptions.AddPageRangeToPrint("1-3"); // add range of pages
            printOptions.AddPageToPrint(5); // add individual page
        }   

        [TestMethod]
        public void TestSize()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintOptions.PageSize currentDimensions = printOptions.PageDimensions;
        }

        [TestMethod]
        public void TestBackgrounds()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.OutputBackgroundImages = true;
            bool currentBackgrounds = printOptions.OutputBackgroundImages;
        }

        [TestMethod]
        public void TestMargins()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintOptions.Margins currentMargins = printOptions.PageMargins;
        }


        [TestMethod]
        public void TestScale()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.ScaleFactor = 0.5;
            double currentScale = printOptions.ScaleFactor;
        }

        [TestMethod]
        public void TestShrinkToFit()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.ShrinkToFit = true;
            bool currentShrinkToFit = printOptions.ShrinkToFit;
        }

        [TestMethod]
        public void PrintWithPrintsPageTest() 
        {
            WebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintDocument printedPage = driver.Print(printOptions);
            Assert.IsTrue(printedPage.AsBase64EncodedString.StartsWith("JVBER"));
        }
    }
}
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.page_height = 27.94  # Use page_width to assign width
    assert print_options.page_height == 27.94
Show full example
import pytest
from selenium import webdriver
from selenium.webdriver.common.print_page_options import PrintOptions

@pytest.fixture()
def driver():
    driver = webdriver.Chrome()
    yield driver
    driver.quit()

def test_orientation(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.orientation = "landscape" ## landscape or portrait
    assert print_options.orientation == "landscape"

def test_range(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.page_ranges = ["1, 2, 3"] ## ["1", "2", "3"] or ["1-3"]
    assert print_options.page_ranges == ["1, 2, 3"]

def test_size(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.page_height = 27.94  # Use page_width to assign width
    assert print_options.page_height == 27.94

def test_margin(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.margin_top = 10
    print_options.margin_bottom = 10
    print_options.margin_left = 10
    print_options.margin_right = 10
    assert print_options.margin_top == 10
    assert print_options.margin_bottom == 10
    assert print_options.margin_left == 10
    assert print_options.margin_right == 10

def test_scale(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.scale = 0.5 ## 0.1 to 2.0
    current_scale = print_options.scale
    assert current_scale == 0.5

def test_background(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.background = True ## True or False
    assert print_options.background is True

def test_shrink_to_fit(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.shrink_to_fit = True ## True or False
    assert print_options.shrink_to_fit is True

Margins

Using the getPageMargin() and setPageMargin() methods, you can set the margin sizes of the page you wish to print — i.e. top, bottom, left, and right margins.

        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        PageMargin margins = new PageMargin(1.0,1.0,1.0,1.0);
        printOptions.setPageMargin(margins);
        double topMargin = margins.getTop();
        double bottomMargin = margins.getBottom();
        double leftMargin = margins.getLeft();
        double rightMargin = margins.getRight();
Show full example
package dev.selenium.interactions;

import org.junit.jupiter.api.Test;
import org.openqa.selenium.print.PageMargin;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.print.PageSize;
import dev.selenium.BaseChromeTest;

public class PrintOptionsTest extends BaseChromeTest {

    @Test
    public void TestOrientation() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setOrientation(PrintOptions.Orientation.LANDSCAPE);
        PrintOptions.Orientation current_orientation = printOptions.getOrientation();
    }

    @Test
    public void TestRange() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setPageRanges("1-2");
        String[] current_range = printOptions.getPageRanges();
    }

    @Test
    public void TestSize() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setPageSize(new PageSize(27.94, 21.59)); // A4 size in cm
        double currentHeight = printOptions.getPageSize().getHeight(); // use getWidth() to retrieve width
    }

    @Test
    public void TestMargins() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        PageMargin margins = new PageMargin(1.0,1.0,1.0,1.0);
        printOptions.setPageMargin(margins);
        double topMargin = margins.getTop();
        double bottomMargin = margins.getBottom();
        double leftMargin = margins.getLeft();
        double rightMargin = margins.getRight();
    }

    @Test
    public void TestScale() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setScale(.50);
        double current_scale = printOptions.getScale();
    }

    @Test
    public void TestBackground() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setBackground(true);
        boolean current_background = printOptions.getBackground();
    }

    @Test
    public void TestShrinkToFit() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setShrinkToFit(true);
        boolean current_shrink_to_fit = printOptions.getShrinkToFit();
    }
}
        public void TestMargins()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintOptions.Margins currentMargins = printOptions.PageMargins;
        }
Show full example
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocumentation.SeleniumInteractions
{
    [TestClass]
    public class PrintOptionsTest
    {
        [TestMethod]
        public void TestOrientation()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://selenium.dev");
            PrintOptions printOptions  = new PrintOptions();
            printOptions.Orientation = PrintOrientation.Landscape;
            PrintOrientation currentOrientation = printOptions.Orientation;
        }

        [TestMethod]
        public void TestRange()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://selenium.dev");
            PrintOptions printOptions  = new PrintOptions();
            printOptions.AddPageRangeToPrint("1-3"); // add range of pages
            printOptions.AddPageToPrint(5); // add individual page
        }   

        [TestMethod]
        public void TestSize()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintOptions.PageSize currentDimensions = printOptions.PageDimensions;
        }

        [TestMethod]
        public void TestBackgrounds()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.OutputBackgroundImages = true;
            bool currentBackgrounds = printOptions.OutputBackgroundImages;
        }

        [TestMethod]
        public void TestMargins()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintOptions.Margins currentMargins = printOptions.PageMargins;
        }


        [TestMethod]
        public void TestScale()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.ScaleFactor = 0.5;
            double currentScale = printOptions.ScaleFactor;
        }

        [TestMethod]
        public void TestShrinkToFit()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.ShrinkToFit = true;
            bool currentShrinkToFit = printOptions.ShrinkToFit;
        }

        [TestMethod]
        public void PrintWithPrintsPageTest() 
        {
            WebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintDocument printedPage = driver.Print(printOptions);
            Assert.IsTrue(printedPage.AsBase64EncodedString.StartsWith("JVBER"));
        }
    }
}
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.margin_top = 10
    print_options.margin_bottom = 10
    print_options.margin_left = 10
    print_options.margin_right = 10
Show full example
import pytest
from selenium import webdriver
from selenium.webdriver.common.print_page_options import PrintOptions

@pytest.fixture()
def driver():
    driver = webdriver.Chrome()
    yield driver
    driver.quit()

def test_orientation(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.orientation = "landscape" ## landscape or portrait
    assert print_options.orientation == "landscape"

def test_range(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.page_ranges = ["1, 2, 3"] ## ["1", "2", "3"] or ["1-3"]
    assert print_options.page_ranges == ["1, 2, 3"]

def test_size(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.page_height = 27.94  # Use page_width to assign width
    assert print_options.page_height == 27.94

def test_margin(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.margin_top = 10
    print_options.margin_bottom = 10
    print_options.margin_left = 10
    print_options.margin_right = 10
    assert print_options.margin_top == 10
    assert print_options.margin_bottom == 10
    assert print_options.margin_left == 10
    assert print_options.margin_right == 10

def test_scale(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.scale = 0.5 ## 0.1 to 2.0
    current_scale = print_options.scale
    assert current_scale == 0.5

def test_background(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.background = True ## True or False
    assert print_options.background is True

def test_shrink_to_fit(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.shrink_to_fit = True ## True or False
    assert print_options.shrink_to_fit is True

Scale

Using getScale() and setScale() methods, you can get/set the scale of the page you wish to print — e.g. 1.0 is 100% or default, 0.25 is 25%, etc.

    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setScale(.50);
        double current_scale = printOptions.getScale();
Show full example
package dev.selenium.interactions;

import org.junit.jupiter.api.Test;
import org.openqa.selenium.print.PageMargin;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.print.PageSize;
import dev.selenium.BaseChromeTest;

public class PrintOptionsTest extends BaseChromeTest {

    @Test
    public void TestOrientation() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setOrientation(PrintOptions.Orientation.LANDSCAPE);
        PrintOptions.Orientation current_orientation = printOptions.getOrientation();
    }

    @Test
    public void TestRange() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setPageRanges("1-2");
        String[] current_range = printOptions.getPageRanges();
    }

    @Test
    public void TestSize() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setPageSize(new PageSize(27.94, 21.59)); // A4 size in cm
        double currentHeight = printOptions.getPageSize().getHeight(); // use getWidth() to retrieve width
    }

    @Test
    public void TestMargins() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        PageMargin margins = new PageMargin(1.0,1.0,1.0,1.0);
        printOptions.setPageMargin(margins);
        double topMargin = margins.getTop();
        double bottomMargin = margins.getBottom();
        double leftMargin = margins.getLeft();
        double rightMargin = margins.getRight();
    }

    @Test
    public void TestScale() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setScale(.50);
        double current_scale = printOptions.getScale();
    }

    @Test
    public void TestBackground() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setBackground(true);
        boolean current_background = printOptions.getBackground();
    }

    @Test
    public void TestShrinkToFit() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setShrinkToFit(true);
        boolean current_shrink_to_fit = printOptions.getShrinkToFit();
    }
}
        public void TestScale()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.ScaleFactor = 0.5;
            double currentScale = printOptions.ScaleFactor;
        }
Show full example
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocumentation.SeleniumInteractions
{
    [TestClass]
    public class PrintOptionsTest
    {
        [TestMethod]
        public void TestOrientation()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://selenium.dev");
            PrintOptions printOptions  = new PrintOptions();
            printOptions.Orientation = PrintOrientation.Landscape;
            PrintOrientation currentOrientation = printOptions.Orientation;
        }

        [TestMethod]
        public void TestRange()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://selenium.dev");
            PrintOptions printOptions  = new PrintOptions();
            printOptions.AddPageRangeToPrint("1-3"); // add range of pages
            printOptions.AddPageToPrint(5); // add individual page
        }   

        [TestMethod]
        public void TestSize()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintOptions.PageSize currentDimensions = printOptions.PageDimensions;
        }

        [TestMethod]
        public void TestBackgrounds()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.OutputBackgroundImages = true;
            bool currentBackgrounds = printOptions.OutputBackgroundImages;
        }

        [TestMethod]
        public void TestMargins()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintOptions.Margins currentMargins = printOptions.PageMargins;
        }


        [TestMethod]
        public void TestScale()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.ScaleFactor = 0.5;
            double currentScale = printOptions.ScaleFactor;
        }

        [TestMethod]
        public void TestShrinkToFit()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.ShrinkToFit = true;
            bool currentShrinkToFit = printOptions.ShrinkToFit;
        }

        [TestMethod]
        public void PrintWithPrintsPageTest() 
        {
            WebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintDocument printedPage = driver.Print(printOptions);
            Assert.IsTrue(printedPage.AsBase64EncodedString.StartsWith("JVBER"));
        }
    }
}
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.scale = 0.5 ## 0.1 to 2.0
    current_scale = print_options.scale
Show full example
import pytest
from selenium import webdriver
from selenium.webdriver.common.print_page_options import PrintOptions

@pytest.fixture()
def driver():
    driver = webdriver.Chrome()
    yield driver
    driver.quit()

def test_orientation(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.orientation = "landscape" ## landscape or portrait
    assert print_options.orientation == "landscape"

def test_range(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.page_ranges = ["1, 2, 3"] ## ["1", "2", "3"] or ["1-3"]
    assert print_options.page_ranges == ["1, 2, 3"]

def test_size(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.page_height = 27.94  # Use page_width to assign width
    assert print_options.page_height == 27.94

def test_margin(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.margin_top = 10
    print_options.margin_bottom = 10
    print_options.margin_left = 10
    print_options.margin_right = 10
    assert print_options.margin_top == 10
    assert print_options.margin_bottom == 10
    assert print_options.margin_left == 10
    assert print_options.margin_right == 10

def test_scale(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.scale = 0.5 ## 0.1 to 2.0
    current_scale = print_options.scale
    assert current_scale == 0.5

def test_background(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.background = True ## True or False
    assert print_options.background is True

def test_shrink_to_fit(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.shrink_to_fit = True ## True or False
    assert print_options.shrink_to_fit is True

Background

Using getBackground() and setBackground() methods, you can get/set whether background colors and images appear — boolean true or false.

        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setBackground(true);
        boolean current_background = printOptions.getBackground();
Show full example
package dev.selenium.interactions;

import org.junit.jupiter.api.Test;
import org.openqa.selenium.print.PageMargin;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.print.PageSize;
import dev.selenium.BaseChromeTest;

public class PrintOptionsTest extends BaseChromeTest {

    @Test
    public void TestOrientation() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setOrientation(PrintOptions.Orientation.LANDSCAPE);
        PrintOptions.Orientation current_orientation = printOptions.getOrientation();
    }

    @Test
    public void TestRange() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setPageRanges("1-2");
        String[] current_range = printOptions.getPageRanges();
    }

    @Test
    public void TestSize() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setPageSize(new PageSize(27.94, 21.59)); // A4 size in cm
        double currentHeight = printOptions.getPageSize().getHeight(); // use getWidth() to retrieve width
    }

    @Test
    public void TestMargins() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        PageMargin margins = new PageMargin(1.0,1.0,1.0,1.0);
        printOptions.setPageMargin(margins);
        double topMargin = margins.getTop();
        double bottomMargin = margins.getBottom();
        double leftMargin = margins.getLeft();
        double rightMargin = margins.getRight();
    }

    @Test
    public void TestScale() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setScale(.50);
        double current_scale = printOptions.getScale();
    }

    @Test
    public void TestBackground() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setBackground(true);
        boolean current_background = printOptions.getBackground();
    }

    @Test
    public void TestShrinkToFit() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setShrinkToFit(true);
        boolean current_shrink_to_fit = printOptions.getShrinkToFit();
    }
}
        public void TestBackgrounds()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.OutputBackgroundImages = true;
            bool currentBackgrounds = printOptions.OutputBackgroundImages;
        }
Show full example
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocumentation.SeleniumInteractions
{
    [TestClass]
    public class PrintOptionsTest
    {
        [TestMethod]
        public void TestOrientation()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://selenium.dev");
            PrintOptions printOptions  = new PrintOptions();
            printOptions.Orientation = PrintOrientation.Landscape;
            PrintOrientation currentOrientation = printOptions.Orientation;
        }

        [TestMethod]
        public void TestRange()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://selenium.dev");
            PrintOptions printOptions  = new PrintOptions();
            printOptions.AddPageRangeToPrint("1-3"); // add range of pages
            printOptions.AddPageToPrint(5); // add individual page
        }   

        [TestMethod]
        public void TestSize()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintOptions.PageSize currentDimensions = printOptions.PageDimensions;
        }

        [TestMethod]
        public void TestBackgrounds()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.OutputBackgroundImages = true;
            bool currentBackgrounds = printOptions.OutputBackgroundImages;
        }

        [TestMethod]
        public void TestMargins()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintOptions.Margins currentMargins = printOptions.PageMargins;
        }


        [TestMethod]
        public void TestScale()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.ScaleFactor = 0.5;
            double currentScale = printOptions.ScaleFactor;
        }

        [TestMethod]
        public void TestShrinkToFit()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.ShrinkToFit = true;
            bool currentShrinkToFit = printOptions.ShrinkToFit;
        }

        [TestMethod]
        public void PrintWithPrintsPageTest() 
        {
            WebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintDocument printedPage = driver.Print(printOptions);
            Assert.IsTrue(printedPage.AsBase64EncodedString.StartsWith("JVBER"));
        }
    }
}
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.background = True ## True or False
Show full example
import pytest
from selenium import webdriver
from selenium.webdriver.common.print_page_options import PrintOptions

@pytest.fixture()
def driver():
    driver = webdriver.Chrome()
    yield driver
    driver.quit()

def test_orientation(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.orientation = "landscape" ## landscape or portrait
    assert print_options.orientation == "landscape"

def test_range(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.page_ranges = ["1, 2, 3"] ## ["1", "2", "3"] or ["1-3"]
    assert print_options.page_ranges == ["1, 2, 3"]

def test_size(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.page_height = 27.94  # Use page_width to assign width
    assert print_options.page_height == 27.94

def test_margin(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.margin_top = 10
    print_options.margin_bottom = 10
    print_options.margin_left = 10
    print_options.margin_right = 10
    assert print_options.margin_top == 10
    assert print_options.margin_bottom == 10
    assert print_options.margin_left == 10
    assert print_options.margin_right == 10

def test_scale(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.scale = 0.5 ## 0.1 to 2.0
    current_scale = print_options.scale
    assert current_scale == 0.5

def test_background(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.background = True ## True or False
    assert print_options.background is True

def test_shrink_to_fit(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.shrink_to_fit = True ## True or False
    assert print_options.shrink_to_fit is True

ShrinkToFit

Using getShrinkToFit() and setShrinkToFit() methods, you can get/set whether the page will shrink-to-fit content on the page — boolean true or false.

        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setShrinkToFit(true);
        boolean current_shrink_to_fit = printOptions.getShrinkToFit();
Show full example
package dev.selenium.interactions;

import org.junit.jupiter.api.Test;
import org.openqa.selenium.print.PageMargin;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.print.PageSize;
import dev.selenium.BaseChromeTest;

public class PrintOptionsTest extends BaseChromeTest {

    @Test
    public void TestOrientation() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setOrientation(PrintOptions.Orientation.LANDSCAPE);
        PrintOptions.Orientation current_orientation = printOptions.getOrientation();
    }

    @Test
    public void TestRange() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setPageRanges("1-2");
        String[] current_range = printOptions.getPageRanges();
    }

    @Test
    public void TestSize() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setPageSize(new PageSize(27.94, 21.59)); // A4 size in cm
        double currentHeight = printOptions.getPageSize().getHeight(); // use getWidth() to retrieve width
    }

    @Test
    public void TestMargins() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        PageMargin margins = new PageMargin(1.0,1.0,1.0,1.0);
        printOptions.setPageMargin(margins);
        double topMargin = margins.getTop();
        double bottomMargin = margins.getBottom();
        double leftMargin = margins.getLeft();
        double rightMargin = margins.getRight();
    }

    @Test
    public void TestScale() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setScale(.50);
        double current_scale = printOptions.getScale();
    }

    @Test
    public void TestBackground() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setBackground(true);
        boolean current_background = printOptions.getBackground();
    }

    @Test
    public void TestShrinkToFit() 
    {
        driver.get("https://www.selenium.dev/");
        PrintOptions printOptions = new PrintOptions();
        printOptions.setShrinkToFit(true);
        boolean current_shrink_to_fit = printOptions.getShrinkToFit();
    }
}
        public void TestShrinkToFit()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.ShrinkToFit = true;
            bool currentShrinkToFit = printOptions.ShrinkToFit;
        }
Show full example
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocumentation.SeleniumInteractions
{
    [TestClass]
    public class PrintOptionsTest
    {
        [TestMethod]
        public void TestOrientation()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://selenium.dev");
            PrintOptions printOptions  = new PrintOptions();
            printOptions.Orientation = PrintOrientation.Landscape;
            PrintOrientation currentOrientation = printOptions.Orientation;
        }

        [TestMethod]
        public void TestRange()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://selenium.dev");
            PrintOptions printOptions  = new PrintOptions();
            printOptions.AddPageRangeToPrint("1-3"); // add range of pages
            printOptions.AddPageToPrint(5); // add individual page
        }   

        [TestMethod]
        public void TestSize()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintOptions.PageSize currentDimensions = printOptions.PageDimensions;
        }

        [TestMethod]
        public void TestBackgrounds()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.OutputBackgroundImages = true;
            bool currentBackgrounds = printOptions.OutputBackgroundImages;
        }

        [TestMethod]
        public void TestMargins()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintOptions.Margins currentMargins = printOptions.PageMargins;
        }


        [TestMethod]
        public void TestScale()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.ScaleFactor = 0.5;
            double currentScale = printOptions.ScaleFactor;
        }

        [TestMethod]
        public void TestShrinkToFit()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.ShrinkToFit = true;
            bool currentShrinkToFit = printOptions.ShrinkToFit;
        }

        [TestMethod]
        public void PrintWithPrintsPageTest() 
        {
            WebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintDocument printedPage = driver.Print(printOptions);
            Assert.IsTrue(printedPage.AsBase64EncodedString.StartsWith("JVBER"));
        }
    }
}
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.shrink_to_fit = True ## True or False
Show full example
import pytest
from selenium import webdriver
from selenium.webdriver.common.print_page_options import PrintOptions

@pytest.fixture()
def driver():
    driver = webdriver.Chrome()
    yield driver
    driver.quit()

def test_orientation(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.orientation = "landscape" ## landscape or portrait
    assert print_options.orientation == "landscape"

def test_range(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.page_ranges = ["1, 2, 3"] ## ["1", "2", "3"] or ["1-3"]
    assert print_options.page_ranges == ["1, 2, 3"]

def test_size(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.page_height = 27.94  # Use page_width to assign width
    assert print_options.page_height == 27.94

def test_margin(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.margin_top = 10
    print_options.margin_bottom = 10
    print_options.margin_left = 10
    print_options.margin_right = 10
    assert print_options.margin_top == 10
    assert print_options.margin_bottom == 10
    assert print_options.margin_left == 10
    assert print_options.margin_right == 10

def test_scale(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.scale = 0.5 ## 0.1 to 2.0
    current_scale = print_options.scale
    assert current_scale == 0.5

def test_background(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.background = True ## True or False
    assert print_options.background is True

def test_shrink_to_fit(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    print_options.shrink_to_fit = True ## True or False
    assert print_options.shrink_to_fit is True

Printing

Once you’ve configured your PrintOptions, you’re ready to print the page. To do this, you can invoke the print function, which generates a PDF representation of the web page. The resulting PDF can be saved to your local storage for further use or distribution. Using PrintsPage(), the print command will return the PDF data in base64-encoded format, which can be decoded and written to a file in your desired location, and using BrowsingContext() will return a String.

There may currently be multiple implementations depending on your language of choice. For example, with Java you have the ability to print using either BrowingContext() or PrintsPage(). Both take PrintOptions() objects as a parameter.

Note: BrowsingContext() is part of Selenium’s BiDi implementation. To enable BiDi see Enabling Bidi

PrintsPage()

        driver.get("https://www.selenium.dev/");
        PrintsPage printer = (PrintsPage) driver;
        PrintOptions printOptions = new PrintOptions();
        Pdf printedPage = printer.print(printOptions);
        Assertions.assertNotNull(printedPage);
Show full example
package dev.selenium.interactions;

import org.openqa.selenium.Pdf;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.openqa.selenium.print.PageMargin;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.PrintsPage;
import dev.selenium.BaseTest;

public class PrintsPageTest extends BaseTest{

    @BeforeEach
    public void setup() {
        ChromeOptions options = getDefaultChromeOptions();
        options.setCapability("webSocketUrl", true);
        driver = new ChromeDriver(options);
    }

    @Test
    public void PrintWithPrintsPageTest() 
    {
        driver.get("https://www.selenium.dev/");
        PrintsPage printer = (PrintsPage) driver;
        PrintOptions printOptions = new PrintOptions();
        Pdf printedPage = printer.print(printOptions);
        Assertions.assertNotNull(printedPage);
    }

    @Test
    public void PrintWithBrowsingContextTest() 
    {
        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.assertTrue(printPage.length() > 0);
    }
}

BrowsingContext()

        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.assertTrue(printPage.length() > 0);
Show full example
package dev.selenium.interactions;

import org.openqa.selenium.Pdf;
import org.openqa.selenium.bidi.browsingcontext.BrowsingContext;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.openqa.selenium.print.PageMargin;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.PrintsPage;
import dev.selenium.BaseTest;

public class PrintsPageTest extends BaseTest{

    @BeforeEach
    public void setup() {
        ChromeOptions options = getDefaultChromeOptions();
        options.setCapability("webSocketUrl", true);
        driver = new ChromeDriver(options);
    }

    @Test
    public void PrintWithPrintsPageTest() 
    {
        driver.get("https://www.selenium.dev/");
        PrintsPage printer = (PrintsPage) driver;
        PrintOptions printOptions = new PrintOptions();
        Pdf printedPage = printer.print(printOptions);
        Assertions.assertNotNull(printedPage);
    }

    @Test
    public void PrintWithBrowsingContextTest() 
    {
        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.assertTrue(printPage.length() > 0);
    }
}
        public void PrintWithPrintsPageTest() 
        {
            WebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintDocument printedPage = driver.Print(printOptions);
            Assert.IsTrue(printedPage.AsBase64EncodedString.StartsWith("JVBER"));
        }
Show full example
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

namespace SeleniumDocumentation.SeleniumInteractions
{
    [TestClass]
    public class PrintOptionsTest
    {
        [TestMethod]
        public void TestOrientation()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://selenium.dev");
            PrintOptions printOptions  = new PrintOptions();
            printOptions.Orientation = PrintOrientation.Landscape;
            PrintOrientation currentOrientation = printOptions.Orientation;
        }

        [TestMethod]
        public void TestRange()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://selenium.dev");
            PrintOptions printOptions  = new PrintOptions();
            printOptions.AddPageRangeToPrint("1-3"); // add range of pages
            printOptions.AddPageToPrint(5); // add individual page
        }   

        [TestMethod]
        public void TestSize()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintOptions.PageSize currentDimensions = printOptions.PageDimensions;
        }

        [TestMethod]
        public void TestBackgrounds()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.OutputBackgroundImages = true;
            bool currentBackgrounds = printOptions.OutputBackgroundImages;
        }

        [TestMethod]
        public void TestMargins()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintOptions.Margins currentMargins = printOptions.PageMargins;
        }


        [TestMethod]
        public void TestScale()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.ScaleFactor = 0.5;
            double currentScale = printOptions.ScaleFactor;
        }

        [TestMethod]
        public void TestShrinkToFit()
        {
            IWebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            printOptions.ShrinkToFit = true;
            bool currentShrinkToFit = printOptions.ShrinkToFit;
        }

        [TestMethod]
        public void PrintWithPrintsPageTest() 
        {
            WebDriver driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.selenium.dev/");
            PrintOptions printOptions = new PrintOptions();
            PrintDocument printedPage = driver.Print(printOptions);
            Assert.IsTrue(printedPage.AsBase64EncodedString.StartsWith("JVBER"));
        }
    }
}

print_page()

    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    pdf = driver.print_page(print_options)
Show full example
import pytest
from selenium import webdriver
from selenium.webdriver.common.print_page_options import PrintOptions

pytest.fixture()
def driver():
    driver = webdriver.Chrome()
    yield driver
    driver.quit()

def test_prints_page(driver):
    driver.get("https://www.selenium.dev/")
    print_options = PrintOptions()
    pdf = driver.print_page(print_options)
    assert len(pdf) > 0

6 - Working with windows and tabs

Janelas e guias

Pegue o idenficador da janela

O WebDriver não faz distinção entre janelas e guias. E se seu site abre uma nova guia ou janela, o Selenium permitirá que você trabalhe usando um identificador. Cada janela tem um identificador único que permanece persistente em uma única sessão. Você pode pegar o identificador atual usando:

        // Navigate to Url
        driver.get("https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html");
        //fetch handle of this
        String currHandle=driver.getWindowHandle();
        assertNotNull(currHandle);
Show full example
package dev.selenium.interactions;

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

public class WindowsTest {

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

Alternando janelas ou guias

Clicar em um link que abre em uma nova janela focará a nova janela ou guia na tela, mas o WebDriver não saberá qual janela que o sistema operacional considera ativa. Para trabalhar com a nova janela você precisará mudar para ela. Se você tiver apenas duas guias ou janelas abertas, e você sabe com qual janela você iniciou, pelo processo de eliminação você pode percorrer as janelas ou guias que o WebDriver pode ver e alternar para aquela que não é o original.

No entanto, o Selenium 4 fornece uma nova API NewWindow que cria uma nova guia (ou) nova janela e muda automaticamente para ela.

        //click on link to open a new window
        driver.findElement(By.linkText("Open new window")).click();
        //fetch handles of all windows, there will be two, [0]- default, [1] - new window
        Object[] windowHandles=driver.getWindowHandles().toArray();
        driver.switchTo().window((String) windowHandles[1]);
        //assert on title of new window
        String title=driver.getTitle();
        assertEquals("Simple Page",title);
Show full example
package dev.selenium.interactions;

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

public class WindowsTest {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  

Fechando uma janela ou guia

Quando você fechar uma janela ou guia e que não é a última janela ou guia aberta em seu navegador, você deve fechá-la e alternar de volta para a janela que você estava usando anteriormente. Supondo que você seguiu a amostra de código na seção anterior, você terá o identificador da janela anterior armazenado em uma variável. Junte isso e você obterá:

        //closing current window
        driver.close();
        //Switch back to the old tab or window
        driver.switchTo().window((String) windowHandles[0]);
Show full example
package dev.selenium.interactions;

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

public class WindowsTest {

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

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

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

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

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

  

Esquecer de voltar para outro gerenciador de janela após fechar uma janela deixará o WebDriver em execução na página agora fechada e acionara uma No Such Window Exception. Você deve trocar de volta para um identificador de janela válido para continuar a execução.

Criar nova janela (ou) nova guia e alternar

Cria uma nova janela (ou) guia e focará a nova janela ou guia na tela. Você não precisa mudar para trabalhar com a nova janela (ou) guia. Se você tiver mais de duas janelas (ou) guias abertas diferentes da nova janela, você pode percorrer as janelas ou guias que o WebDriver pode ver e mudar para aquela que não é a original.

Nota: este recurso funciona com Selenium 4 e versões posteriores.

        //Opens a new tab and switches to new tab
        driver.switchTo().newWindow(WindowType.TAB);
        assertEquals("",driver.getTitle());
        
        //Opens a new window and switches to new window
        driver.switchTo().newWindow(WindowType.WINDOW);
        assertEquals("",driver.getTitle());
Show full example
package dev.selenium.interactions;

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

public class WindowsTest {

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

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

Opens a new tab and switches to new tab

    driver.switch_to.new_window(:tab)
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Windows' do
  let(:driver) { start_session }

  it 'opens new tab' do
    driver.switch_to.new_window(:tab)

    expect(driver.window_handles.size).to eq 2
  end

  it 'opens new window' do
    driver.switch_to.new_window(:window)

    expect(driver.window_handles.size).to eq 2
  end
end

Opens a new window and switches to new window

    driver.switch_to.new_window(:window)
Show full example
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe 'Windows' do
  let(:driver) { start_session }

  it 'opens new tab' do
    driver.switch_to.new_window(:tab)

    expect(driver.window_handles.size).to eq 2
  end

  it 'opens new window' do
    driver.switch_to.new_window(:window)

    expect(driver.window_handles.size).to eq 2
  end
end
Opens a new tab and switches to new tab
    await driver.switchTo().newWindow('tab');
Show full example
const {Builder, By} = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
const assert = require("node:assert");
let opts = new chrome.Options();
opts.addArguments('--headless');
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let imgMagicNumber = 'iVBOR'
let base64Code

describe('Interactions - Windows', function () {
  let driver;
  before(async function () {
    driver = await new Builder().forBrowser('chrome').setChromeOptions(opts).build();
  });

  after(async () => await driver.quit());

  it('Should be able to print page to pdf', async function () {

    await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
    let base64 = await driver.printPage({pageRanges: ["1-2"]});
    // page can be saved as a PDF as below
    // await fs.writeFileSync('./test.pdf', base64, 'base64');

    base64Code = base64.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, pdfMagicNumber)
  });

  it('Should be able to get text using executeScript', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');
    // Stores the header element
    let header = await driver.findElement(By.css('h1'));

    // Executing JavaScript to capture innerText of header element
    let text = await driver.executeScript('return arguments[0].innerText', header);
    assert.strictEqual(text, `Type Stuff`)
  });

  it('Should be able to take Element Screenshot', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');

    let header = await driver.findElement(By.css('h1'));
    // Captures the element screenshot
    let encodedString = await header.takeScreenshot(true);
    // save screenshot as below
    // await fs.writeFileSync('./image.png', encodedString, 'base64');
    base64Code = encodedString.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, imgMagicNumber)
  });

  it('Should be able to takeScreenshot', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');

    // Captures the screenshot
    let encodedString = await driver.takeScreenshot();
    // save screenshot as below
    // await fs.writeFileSync('./image.png', encodedString, 'base64');
    base64Code = encodedString.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, imgMagicNumber)
  });

  it('Should be able to switch to newWindow and newTab and close', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');
    const initialWindow = await driver.getAllWindowHandles();
    assert.strictEqual(initialWindow.length, 1)

    // Opens a new tab and switches to new tab
    await driver.switchTo().newWindow('tab');
    const browserTabs = await driver.getAllWindowHandles();
    assert.strictEqual(browserTabs.length, 2)

    // Opens a new window and switches to new window
    await driver.switchTo().newWindow('window');
    const windows = await driver.getAllWindowHandles();
    assert.strictEqual(windows.length, 3)

    //Close the tab or window
    await driver.close();

    //Switch back to the old tab or window
    await driver.switchTo().window(windows[1]);

    const windowsAfterClose = await driver.getAllWindowHandles();
    assert.strictEqual(windowsAfterClose.length, 2);
  });

  it('Should be able to getWindow Size', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');

    // Access each dimension individually
    const { width, height } = await driver.manage().window().getRect();

    // Or store the dimensions and query them later
    const rect = await driver.manage().window().getRect();
    const windowWidth = rect.width;
    const windowHeight = rect.height;

    assert.ok(windowWidth>0);
    assert.ok(windowHeight>0);
  });

  it('Should be able to getWindow position', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');

    // Access each dimension individually
    const { x, y } = await driver.manage().window().getRect();

    // Or store the dimensions and query them later
    const rect = await driver.manage().window().getRect();
    const x1 = rect.x;
    const y1 = rect.y;

    assert.ok(x1>=0);
    assert.ok(y1>=0);
  });
});
Opens a new window and switches to new window:
    await driver.switchTo().newWindow('window');
Show full example
const {Builder, By} = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
const assert = require("node:assert");
let opts = new chrome.Options();
opts.addArguments('--headless');
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let imgMagicNumber = 'iVBOR'
let base64Code

describe('Interactions - Windows', function () {
  let driver;
  before(async function () {
    driver = await new Builder().forBrowser('chrome').setChromeOptions(opts).build();
  });

  after(async () => await driver.quit());

  it('Should be able to print page to pdf', async function () {

    await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
    let base64 = await driver.printPage({pageRanges: ["1-2"]});
    // page can be saved as a PDF as below
    // await fs.writeFileSync('./test.pdf', base64, 'base64');

    base64Code = base64.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, pdfMagicNumber)
  });

  it('Should be able to get text using executeScript', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');
    // Stores the header element
    let header = await driver.findElement(By.css('h1'));

    // Executing JavaScript to capture innerText of header element
    let text = await driver.executeScript('return arguments[0].innerText', header);
    assert.strictEqual(text, `Type Stuff`)
  });

  it('Should be able to take Element Screenshot', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');

    let header = await driver.findElement(By.css('h1'));
    // Captures the element screenshot
    let encodedString = await header.takeScreenshot(true);
    // save screenshot as below
    // await fs.writeFileSync('./image.png', encodedString, 'base64');
    base64Code = encodedString.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, imgMagicNumber)
  });

  it('Should be able to takeScreenshot', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');

    // Captures the screenshot
    let encodedString = await driver.takeScreenshot();
    // save screenshot as below
    // await fs.writeFileSync('./image.png', encodedString, 'base64');
    base64Code = encodedString.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, imgMagicNumber)
  });

  it('Should be able to switch to newWindow and newTab and close', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');
    const initialWindow = await driver.getAllWindowHandles();
    assert.strictEqual(initialWindow.length, 1)

    // Opens a new tab and switches to new tab
    await driver.switchTo().newWindow('tab');
    const browserTabs = await driver.getAllWindowHandles();
    assert.strictEqual(browserTabs.length, 2)

    // Opens a new window and switches to new window
    await driver.switchTo().newWindow('window');
    const windows = await driver.getAllWindowHandles();
    assert.strictEqual(windows.length, 3)

    //Close the tab or window
    await driver.close();

    //Switch back to the old tab or window
    await driver.switchTo().window(windows[1]);

    const windowsAfterClose = await driver.getAllWindowHandles();
    assert.strictEqual(windowsAfterClose.length, 2);
  });

  it('Should be able to getWindow Size', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');

    // Access each dimension individually
    const { width, height } = await driver.manage().window().getRect();

    // Or store the dimensions and query them later
    const rect = await driver.manage().window().getRect();
    const windowWidth = rect.width;
    const windowHeight = rect.height;

    assert.ok(windowWidth>0);
    assert.ok(windowHeight>0);
  });

  it('Should be able to getWindow position', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');

    // Access each dimension individually
    const { x, y } = await driver.manage().window().getRect();

    // Or store the dimensions and query them later
    const rect = await driver.manage().window().getRect();
    const x1 = rect.x;
    const y1 = rect.y;

    assert.ok(x1>=0);
    assert.ok(y1>=0);
  });
});
// Opens a new tab and switches to new tab
driver.switchTo().newWindow(WindowType.TAB)

// Opens a new window and switches to new window
driver.switchTo().newWindow(WindowType.WINDOW)
  

Sair do navegador no final de uma sessão

Quando você terminar a sessão do navegador, você deve chamar a função quit(), em vez de fechar:

        //quitting driver
        driver.quit(); //close all windows
Show full example
package dev.selenium.interactions;

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

public class WindowsTest {

    @Test
    public void windowsExampleCode() {
        
    	WebDriver driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
        // Navigate to Url
        driver.get("https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html");
        //fetch handle of this
        String currHandle=driver.getWindowHandle();
        assertNotNull(currHandle);
        
        //click on link to open a new window
        driver.findElement(By.linkText("Open new window")).click();
        //fetch handles of all windows, there will be two, [0]- default, [1] - new window
        Object[] windowHandles=driver.getWindowHandles().toArray();
        driver.switchTo().window((String) windowHandles[1]);
        //assert on title of new window
        String title=driver.getTitle();
        assertEquals("Simple Page",title);
        
        //closing current window
        driver.close();
        //Switch back to the old tab or window
        driver.switchTo().window((String) windowHandles[0]);
        
        //Opens a new tab and switches to new tab
        driver.switchTo().newWindow(WindowType.TAB);
        assertEquals("",driver.getTitle());
        
        //Opens a new window and switches to new window
        driver.switchTo().newWindow(WindowType.WINDOW);
        assertEquals("",driver.getTitle());
             
        //quitting driver
        driver.quit(); //close all windows
	   
   	}
}
driver.quit()
            //quitting driver
              driver.Quit(); //close all windows
Show full example
using System;
  using Microsoft.VisualStudio.TestTools.UnitTesting;
  using OpenQA.Selenium;
  using OpenQA.Selenium.Chrome;
  using System.Collections.Generic;
  namespace SeleniumDocs.Interactions
  {
      [TestClass]
      public class WindowsTest
      {
          [TestMethod]
          public void TestWindowCommands()
          {
              WebDriver driver = new ChromeDriver();
              driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
  
              // Navigate to Url
              driver.Url="https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html";
              //fetch handle of this
              String currHandle = driver.CurrentWindowHandle;
              Assert.IsNotNull(currHandle);
  
              //click on link to open a new window
              driver.FindElement(By.LinkText("Open new window")).Click();
              //fetch handles of all windows, there will be two, [0]- default, [1] - new window
              IList<string> windowHandles = new List<string>(driver.WindowHandles);
              driver.SwitchTo().Window(windowHandles[1]);
              //assert on title of new window
              String title = driver.Title;
              Assert.AreEqual("Simple Page", title);
  
              //closing current window
              driver.Close();
              //Switch back to the old tab or window
              driver.SwitchTo().Window(windowHandles[0]);
  
              //Opens a new tab and switches to new tab
              driver.SwitchTo().NewWindow(WindowType.Tab);
              Assert.AreEqual("", driver.Title);
  
              //Opens a new window and switches to new window
              driver.SwitchTo().NewWindow(WindowType.Window);
              Assert.AreEqual("", driver.Title);
  
              //quitting driver
              driver.Quit(); //close all windows
          }
      }
  }
  
driver.quit
await driver.quit();
driver.quit()
  • quit() irá:
    • Fechar todas as janelas e guias associadas a essa sessão do WebDriver
    • Fechar o processo do navegador
    • Fechar o processo do driver em segundo plano
    • Notificar o Selenium Grid de que o navegador não está mais em uso para que possa ser usado por outra sessão (se você estiver usando Selenium Grid)

A falha em encerrar deixará processos e portas extras em segundo plano rodando em sua máquina, o que pode causar problemas mais tarde.

Algumas estruturas de teste oferecem métodos e anotações em que você pode ligar para derrubar no final de um teste.

/**
 * Example using JUnit
 * https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/AfterAll.html
 */
@AfterAll
public static void tearDown() {
    driver.quit();
}
  
    # unittest teardown
    # https://docs.python.org/3/library/unittest.html?highlight=teardown#unittest.TestCase.tearDown
def tearDown(self):
    self.driver.quit()
  
/*
    Example using Visual Studio's UnitTesting
    https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.aspx
*/
[TestCleanup]
public void TearDown()
{
    driver.Quit();
}
  
    # UnitTest Teardown
    # https://www.rubydoc.info/github/test-unit/test-unit/Test/Unit/TestCase
def teardown
    @driver.quit
end
  
/**
 * Example using Mocha
 * https://mochajs.org/#hooks
 */
after('Tear down', async function () {
  await driver.quit();
});
  
/**
 * Example using JUnit
 * https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/AfterAll.html
 */
@AfterAll
fun tearDown() {
    driver.quit()
}
  

Se não estiver executando o WebDriver em um contexto de teste, você pode considerar o uso do try/finally que é oferecido pela maioria das linguagens para que uma exceção ainda limpe a sessão do WebDriver.

try {
    //WebDriver code here...
} finally {
    driver.quit();
}
  
try:
    #WebDriver code here...
finally:
    driver.quit()
  
try {
    //WebDriver code here...
} finally {
    driver.Quit();
}
  
begin
    #WebDriver code here...
ensure
    driver.quit
end
  
try {
    //WebDriver code here...
} finally {
    await driver.quit();
}
  
try {
    //WebDriver code here...
} finally {
    driver.quit()
}
  

O WebDriver do Python agora suporta o gerenciador de contexto python, que ao usar a palavra-chave with pode encerrar automaticamente o driver no fim da execução.

with webdriver.Firefox() as driver:
  # WebDriver code here...

# WebDriver will automatically quit after indentation

Gerenciamento de janelas

A resolução da tela pode impactar como seu aplicativo da web é renderizado, então WebDriver fornece mecanismos para mover e redimensionar a janela do navegador.

Coletar o tamanho da janela

Obtém o tamanho da janela do navegador em pixels.

//Access each dimension individually
int width = driver.manage().window().getSize().getWidth();
int height = driver.manage().window().getSize().getHeight();

//Or store the dimensions and query them later
Dimension size = driver.manage().window().getSize();
int width1 = size.getWidth();
int height1 = size.getHeight();
  
    # Access each dimension individually
width = driver.get_window_size().get("width")
height = driver.get_window_size().get("height")

    # Or store the dimensions and query them later
size = driver.get_window_size()
width1 = size.get("width")
height1 = size.get("height")
  
//Access each dimension individually
int width = driver.Manage().Window.Size.Width;
int height = driver.Manage().Window.Size.Height;

//Or store the dimensions and query them later
System.Drawing.Size size = driver.Manage().Window.Size;
int width1 = size.Width;
int height1 = size.Height;
  
    # Access each dimension individually
width = driver.manage.window.size.width
height = driver.manage.window.size.height

    # Or store the dimensions and query them later
size = driver.manage.window.size
width1 = size.width
height1 = size.height
  
Access each dimension individually
    const { width, height } = await driver.manage().window().getRect();
Show full example
const {Builder, By} = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
const assert = require("node:assert");
let opts = new chrome.Options();
opts.addArguments('--headless');
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let imgMagicNumber = 'iVBOR'
let base64Code

describe('Interactions - Windows', function () {
  let driver;
  before(async function () {
    driver = await new Builder().forBrowser('chrome').setChromeOptions(opts).build();
  });

  after(async () => await driver.quit());

  it('Should be able to print page to pdf', async function () {

    await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
    let base64 = await driver.printPage({pageRanges: ["1-2"]});
    // page can be saved as a PDF as below
    // await fs.writeFileSync('./test.pdf', base64, 'base64');

    base64Code = base64.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, pdfMagicNumber)
  });

  it('Should be able to get text using executeScript', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');
    // Stores the header element
    let header = await driver.findElement(By.css('h1'));

    // Executing JavaScript to capture innerText of header element
    let text = await driver.executeScript('return arguments[0].innerText', header);
    assert.strictEqual(text, `Type Stuff`)
  });

  it('Should be able to take Element Screenshot', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');

    let header = await driver.findElement(By.css('h1'));
    // Captures the element screenshot
    let encodedString = await header.takeScreenshot(true);
    // save screenshot as below
    // await fs.writeFileSync('./image.png', encodedString, 'base64');
    base64Code = encodedString.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, imgMagicNumber)
  });

  it('Should be able to takeScreenshot', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');

    // Captures the screenshot
    let encodedString = await driver.takeScreenshot();
    // save screenshot as below
    // await fs.writeFileSync('./image.png', encodedString, 'base64');
    base64Code = encodedString.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, imgMagicNumber)
  });

  it('Should be able to switch to newWindow and newTab and close', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');
    const initialWindow = await driver.getAllWindowHandles();
    assert.strictEqual(initialWindow.length, 1)

    // Opens a new tab and switches to new tab
    await driver.switchTo().newWindow('tab');
    const browserTabs = await driver.getAllWindowHandles();
    assert.strictEqual(browserTabs.length, 2)

    // Opens a new window and switches to new window
    await driver.switchTo().newWindow('window');
    const windows = await driver.getAllWindowHandles();
    assert.strictEqual(windows.length, 3)

    //Close the tab or window
    await driver.close();

    //Switch back to the old tab or window
    await driver.switchTo().window(windows[1]);

    const windowsAfterClose = await driver.getAllWindowHandles();
    assert.strictEqual(windowsAfterClose.length, 2);
  });

  it('Should be able to getWindow Size', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');

    // Access each dimension individually
    const { width, height } = await driver.manage().window().getRect();

    // Or store the dimensions and query them later
    const rect = await driver.manage().window().getRect();
    const windowWidth = rect.width;
    const windowHeight = rect.height;

    assert.ok(windowWidth>0);
    assert.ok(windowHeight>0);
  });

  it('Should be able to getWindow position', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');

    // Access each dimension individually
    const { x, y } = await driver.manage().window().getRect();

    // Or store the dimensions and query them later
    const rect = await driver.manage().window().getRect();
    const x1 = rect.x;
    const y1 = rect.y;

    assert.ok(x1>=0);
    assert.ok(y1>=0);
  });
});
(or) store the dimensions and query them later
    const rect = await driver.manage().window().getRect();
    const windowWidth = rect.width;
    const windowHeight = rect.height;
Show full example
const {Builder, By} = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
const assert = require("node:assert");
let opts = new chrome.Options();
opts.addArguments('--headless');
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let imgMagicNumber = 'iVBOR'
let base64Code

describe('Interactions - Windows', function () {
  let driver;
  before(async function () {
    driver = await new Builder().forBrowser('chrome').setChromeOptions(opts).build();
  });

  after(async () => await driver.quit());

  it('Should be able to print page to pdf', async function () {

    await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
    let base64 = await driver.printPage({pageRanges: ["1-2"]});
    // page can be saved as a PDF as below
    // await fs.writeFileSync('./test.pdf', base64, 'base64');

    base64Code = base64.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, pdfMagicNumber)
  });

  it('Should be able to get text using executeScript', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');
    // Stores the header element
    let header = await driver.findElement(By.css('h1'));

    // Executing JavaScript to capture innerText of header element
    let text = await driver.executeScript('return arguments[0].innerText', header);
    assert.strictEqual(text, `Type Stuff`)
  });

  it('Should be able to take Element Screenshot', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');

    let header = await driver.findElement(By.css('h1'));
    // Captures the element screenshot
    let encodedString = await header.takeScreenshot(true);
    // save screenshot as below
    // await fs.writeFileSync('./image.png', encodedString, 'base64');
    base64Code = encodedString.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, imgMagicNumber)
  });

  it('Should be able to takeScreenshot', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');

    // Captures the screenshot
    let encodedString = await driver.takeScreenshot();
    // save screenshot as below
    // await fs.writeFileSync('./image.png', encodedString, 'base64');
    base64Code = encodedString.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, imgMagicNumber)
  });

  it('Should be able to switch to newWindow and newTab and close', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');
    const initialWindow = await driver.getAllWindowHandles();
    assert.strictEqual(initialWindow.length, 1)

    // Opens a new tab and switches to new tab
    await driver.switchTo().newWindow('tab');
    const browserTabs = await driver.getAllWindowHandles();
    assert.strictEqual(browserTabs.length, 2)

    // Opens a new window and switches to new window
    await driver.switchTo().newWindow('window');
    const windows = await driver.getAllWindowHandles();
    assert.strictEqual(windows.length, 3)

    //Close the tab or window
    await driver.close();

    //Switch back to the old tab or window
    await driver.switchTo().window(windows[1]);

    const windowsAfterClose = await driver.getAllWindowHandles();
    assert.strictEqual(windowsAfterClose.length, 2);
  });

  it('Should be able to getWindow Size', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');

    // Access each dimension individually
    const { width, height } = await driver.manage().window().getRect();

    // Or store the dimensions and query them later
    const rect = await driver.manage().window().getRect();
    const windowWidth = rect.width;
    const windowHeight = rect.height;

    assert.ok(windowWidth>0);
    assert.ok(windowHeight>0);
  });

  it('Should be able to getWindow position', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');

    // Access each dimension individually
    const { x, y } = await driver.manage().window().getRect();

    // Or store the dimensions and query them later
    const rect = await driver.manage().window().getRect();
    const x1 = rect.x;
    const y1 = rect.y;

    assert.ok(x1>=0);
    assert.ok(y1>=0);
  });
});
//Access each dimension individually
val width = driver.manage().window().size.width
val height = driver.manage().window().size.height

//Or store the dimensions and query them later
val size = driver.manage().window().size
val width1 = size.width
val height1 = size.height
  

Definir o tamanho da janela

Restaura a janela e define o tamanho da janela.

driver.manage().window().setSize(new Dimension(1024, 768));
driver.set_window_size(1024, 768)
driver.Manage().Window.Size = new Size(1024, 768);
driver.manage.window.resize_to(1024,768)
await driver.manage().window().setRect({ width: 1024, height: 768 });
driver.manage().window().size = Dimension(1024, 768)

Coletar posição da janela

Busca as coordenadas da coordenada superior esquerda da janela do navegador.

// Access each dimension individually
int x = driver.manage().window().getPosition().getX();
int y = driver.manage().window().getPosition().getY();

// Or store the dimensions and query them later
Point position = driver.manage().window().getPosition();
int x1 = position.getX();
int y1 = position.getY();
  
    # Access each dimension individually
x = driver.get_window_position().get('x')
y = driver.get_window_position().get('y')

    # Or store the dimensions and query them later
position = driver.get_window_position()
x1 = position.get('x')
y1 = position.get('y')
  
//Access each dimension individually
int x = driver.Manage().Window.Position.X;
int y = driver.Manage().Window.Position.Y;

//Or store the dimensions and query them later
Point position = driver.Manage().Window.Position;
int x1 = position.X;
int y1 = position.Y;
  
    #Access each dimension individually
x = driver.manage.window.position.x
y = driver.manage.window.position.y

    # Or store the dimensions and query them later
rect  = driver.manage.window.rect
x1 = rect.x
y1 = rect.y
  
Access each dimension individually
    const { x, y } = await driver.manage().window().getRect();
Show full example
const {Builder, By} = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
const assert = require("node:assert");
let opts = new chrome.Options();
opts.addArguments('--headless');
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let imgMagicNumber = 'iVBOR'
let base64Code

describe('Interactions - Windows', function () {
  let driver;
  before(async function () {
    driver = await new Builder().forBrowser('chrome').setChromeOptions(opts).build();
  });

  after(async () => await driver.quit());

  it('Should be able to print page to pdf', async function () {

    await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
    let base64 = await driver.printPage({pageRanges: ["1-2"]});
    // page can be saved as a PDF as below
    // await fs.writeFileSync('./test.pdf', base64, 'base64');

    base64Code = base64.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, pdfMagicNumber)
  });

  it('Should be able to get text using executeScript', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');
    // Stores the header element
    let header = await driver.findElement(By.css('h1'));

    // Executing JavaScript to capture innerText of header element
    let text = await driver.executeScript('return arguments[0].innerText', header);
    assert.strictEqual(text, `Type Stuff`)
  });

  it('Should be able to take Element Screenshot', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');

    let header = await driver.findElement(By.css('h1'));
    // Captures the element screenshot
    let encodedString = await header.takeScreenshot(true);
    // save screenshot as below
    // await fs.writeFileSync('./image.png', encodedString, 'base64');
    base64Code = encodedString.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, imgMagicNumber)
  });

  it('Should be able to takeScreenshot', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');

    // Captures the screenshot
    let encodedString = await driver.takeScreenshot();
    // save screenshot as below
    // await fs.writeFileSync('./image.png', encodedString, 'base64');
    base64Code = encodedString.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, imgMagicNumber)
  });

  it('Should be able to switch to newWindow and newTab and close', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');
    const initialWindow = await driver.getAllWindowHandles();
    assert.strictEqual(initialWindow.length, 1)

    // Opens a new tab and switches to new tab
    await driver.switchTo().newWindow('tab');
    const browserTabs = await driver.getAllWindowHandles();
    assert.strictEqual(browserTabs.length, 2)

    // Opens a new window and switches to new window
    await driver.switchTo().newWindow('window');
    const windows = await driver.getAllWindowHandles();
    assert.strictEqual(windows.length, 3)

    //Close the tab or window
    await driver.close();

    //Switch back to the old tab or window
    await driver.switchTo().window(windows[1]);

    const windowsAfterClose = await driver.getAllWindowHandles();
    assert.strictEqual(windowsAfterClose.length, 2);
  });

  it('Should be able to getWindow Size', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');

    // Access each dimension individually
    const { width, height } = await driver.manage().window().getRect();

    // Or store the dimensions and query them later
    const rect = await driver.manage().window().getRect();
    const windowWidth = rect.width;
    const windowHeight = rect.height;

    assert.ok(windowWidth>0);
    assert.ok(windowHeight>0);
  });

  it('Should be able to getWindow position', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');

    // Access each dimension individually
    const { x, y } = await driver.manage().window().getRect();

    // Or store the dimensions and query them later
    const rect = await driver.manage().window().getRect();
    const x1 = rect.x;
    const y1 = rect.y;

    assert.ok(x1>=0);
    assert.ok(y1>=0);
  });
});
(or) store the dimensions and query them later
    const rect = await driver.manage().window().getRect();
    const x1 = rect.x;
    const y1 = rect.y;
Show full example
const {Builder, By} = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
const assert = require("node:assert");
let opts = new chrome.Options();
opts.addArguments('--headless');
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let imgMagicNumber = 'iVBOR'
let base64Code

describe('Interactions - Windows', function () {
  let driver;
  before(async function () {
    driver = await new Builder().forBrowser('chrome').setChromeOptions(opts).build();
  });

  after(async () => await driver.quit());

  it('Should be able to print page to pdf', async function () {

    await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
    let base64 = await driver.printPage({pageRanges: ["1-2"]});
    // page can be saved as a PDF as below
    // await fs.writeFileSync('./test.pdf', base64, 'base64');

    base64Code = base64.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, pdfMagicNumber)
  });

  it('Should be able to get text using executeScript', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');
    // Stores the header element
    let header = await driver.findElement(By.css('h1'));

    // Executing JavaScript to capture innerText of header element
    let text = await driver.executeScript('return arguments[0].innerText', header);
    assert.strictEqual(text, `Type Stuff`)
  });

  it('Should be able to take Element Screenshot', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');

    let header = await driver.findElement(By.css('h1'));
    // Captures the element screenshot
    let encodedString = await header.takeScreenshot(true);
    // save screenshot as below
    // await fs.writeFileSync('./image.png', encodedString, 'base64');
    base64Code = encodedString.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, imgMagicNumber)
  });

  it('Should be able to takeScreenshot', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');

    // Captures the screenshot
    let encodedString = await driver.takeScreenshot();
    // save screenshot as below
    // await fs.writeFileSync('./image.png', encodedString, 'base64');
    base64Code = encodedString.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, imgMagicNumber)
  });

  it('Should be able to switch to newWindow and newTab and close', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');
    const initialWindow = await driver.getAllWindowHandles();
    assert.strictEqual(initialWindow.length, 1)

    // Opens a new tab and switches to new tab
    await driver.switchTo().newWindow('tab');
    const browserTabs = await driver.getAllWindowHandles();
    assert.strictEqual(browserTabs.length, 2)

    // Opens a new window and switches to new window
    await driver.switchTo().newWindow('window');
    const windows = await driver.getAllWindowHandles();
    assert.strictEqual(windows.length, 3)

    //Close the tab or window
    await driver.close();

    //Switch back to the old tab or window
    await driver.switchTo().window(windows[1]);

    const windowsAfterClose = await driver.getAllWindowHandles();
    assert.strictEqual(windowsAfterClose.length, 2);
  });

  it('Should be able to getWindow Size', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');

    // Access each dimension individually
    const { width, height } = await driver.manage().window().getRect();

    // Or store the dimensions and query them later
    const rect = await driver.manage().window().getRect();
    const windowWidth = rect.width;
    const windowHeight = rect.height;

    assert.ok(windowWidth>0);
    assert.ok(windowHeight>0);
  });

  it('Should be able to getWindow position', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');

    // Access each dimension individually
    const { x, y } = await driver.manage().window().getRect();

    // Or store the dimensions and query them later
    const rect = await driver.manage().window().getRect();
    const x1 = rect.x;
    const y1 = rect.y;

    assert.ok(x1>=0);
    assert.ok(y1>=0);
  });
});
// Access each dimension individually
val x = driver.manage().window().position.x
val y = driver.manage().window().position.y

// Or store the dimensions and query them later
val position = driver.manage().window().position
val x1 = position.x
val y1 = position.y

  

Definir posição da janela

Move a janela para a posição escolhida.

// Move the window to the top left of the primary monitor
driver.manage().window().setPosition(new Point(0, 0));
  
    # Move the window to the top left of the primary monitor
driver.set_window_position(0, 0)
  
// Move the window to the top left of the primary monitor
driver.Manage().Window.Position = new Point(0, 0);
  
driver.manage.window.move_to(0,0)
  
// Move the window to the top left of the primary monitor
await driver.manage().window().setRect({ x: 0, y: 0 });
  
// Move the window to the top left of the primary monitor
driver.manage().window().position = Point(0,0)
    

Maximizar janela

Aumenta a janela. Para a maioria dos sistemas operacionais, a janela irá preencher a tela, sem bloquear os próprios menus do sistema operacional e barras de ferramentas.

driver.manage().window().maximize();
driver.maximize_window()
driver.Manage().Window.Maximize();
driver.manage.window.maximize
await driver.manage().window().maximize();
driver.manage().window().maximize()

Minimizar janela

Minimiza a janela do contexto de navegação atual. O comportamento exato deste comando é específico para gerenciadores de janela individuais.

Minimizar Janela normalmente oculta a janela na bandeja do sistema.

Nota: este recurso funciona com Selenium 4 e versões posteriores.

driver.manage().window().minimize();
driver.minimize_window()
driver.Manage().Window.Minimize();
driver.manage.window.minimize
await driver.manage().window().minimize();
driver.manage().window().minimize()

Janela em tamanho cheio

Preenche a tela inteira, semelhante a pressionar F11 na maioria dos navegadores.

driver.manage().window().fullscreen();
driver.fullscreen_window()
driver.Manage().Window.FullScreen();
driver.manage.window.full_screen
await driver.manage().window().fullscreen();
driver.manage().window().fullscreen()

TakeScreenshot

Usado para capturar a tela do contexto de navegação atual. O endpoint WebDriver screenshot retorna a captura de tela codificada no formato Base64.

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.*;
import org.openqa.selenium.*;

public class SeleniumTakeScreenshot {
    public static void main(String args[]) throws IOException {
        WebDriver driver = new ChromeDriver();
        driver.get("http://www.example.com");
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, new File("./image.png"));
        driver.quit();
    }
}
  
from selenium import webdriver

driver = webdriver.Chrome()

    # Navigate to url
driver.get("http://www.example.com")

    # Returns and base64 encoded string into image
driver.save_screenshot('./image.png')

driver.quit()
  using OpenQA.Selenium;
  using OpenQA.Selenium.Chrome;
  using OpenQA.Selenium.Support.UI;

  var driver = new ChromeDriver();
  driver.Navigate().GoToUrl("http://www.example.com");
  Screenshot screenshot = (driver as ITakesScreenshot).GetScreenshot();
  screenshot.SaveAsFile("screenshot.png", ScreenshotImageFormat.Png); // Format values are Bmp, Gif, Jpeg, Png, Tiff
  
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :chrome

begin
  driver.get 'https://example.com/'

      # Takes and Stores the screenshot in specified path
  driver.save_screenshot('./image.png')

end
  
    // Captures the screenshot
    let encodedString = await driver.takeScreenshot();
    // save screenshot as below
    // await fs.writeFileSync('./image.png', encodedString, 'base64');
Show full example
const {Builder, By} = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
const assert = require("node:assert");
let opts = new chrome.Options();
opts.addArguments('--headless');
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let imgMagicNumber = 'iVBOR'
let base64Code

describe('Interactions - Windows', function () {
  let driver;
  before(async function () {
    driver = await new Builder().forBrowser('chrome').setChromeOptions(opts).build();
  });

  after(async () => await driver.quit());

  it('Should be able to print page to pdf', async function () {

    await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
    let base64 = await driver.printPage({pageRanges: ["1-2"]});
    // page can be saved as a PDF as below
    // await fs.writeFileSync('./test.pdf', base64, 'base64');

    base64Code = base64.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, pdfMagicNumber)
  });

  it('Should be able to get text using executeScript', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');
    // Stores the header element
    let header = await driver.findElement(By.css('h1'));

    // Executing JavaScript to capture innerText of header element
    let text = await driver.executeScript('return arguments[0].innerText', header);
    assert.strictEqual(text, `Type Stuff`)
  });

  it('Should be able to take Element Screenshot', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');

    let header = await driver.findElement(By.css('h1'));
    // Captures the element screenshot
    let encodedString = await header.takeScreenshot(true);
    // save screenshot as below
    // await fs.writeFileSync('./image.png', encodedString, 'base64');
    base64Code = encodedString.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, imgMagicNumber)
  });

  it('Should be able to takeScreenshot', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');

    // Captures the screenshot
    let encodedString = await driver.takeScreenshot();
    // save screenshot as below
    // await fs.writeFileSync('./image.png', encodedString, 'base64');
    base64Code = encodedString.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, imgMagicNumber)
  });

  it('Should be able to switch to newWindow and newTab and close', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');
    const initialWindow = await driver.getAllWindowHandles();
    assert.strictEqual(initialWindow.length, 1)

    // Opens a new tab and switches to new tab
    await driver.switchTo().newWindow('tab');
    const browserTabs = await driver.getAllWindowHandles();
    assert.strictEqual(browserTabs.length, 2)

    // Opens a new window and switches to new window
    await driver.switchTo().newWindow('window');
    const windows = await driver.getAllWindowHandles();
    assert.strictEqual(windows.length, 3)

    //Close the tab or window
    await driver.close();

    //Switch back to the old tab or window
    await driver.switchTo().window(windows[1]);

    const windowsAfterClose = await driver.getAllWindowHandles();
    assert.strictEqual(windowsAfterClose.length, 2);
  });

  it('Should be able to getWindow Size', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');

    // Access each dimension individually
    const { width, height } = await driver.manage().window().getRect();

    // Or store the dimensions and query them later
    const rect = await driver.manage().window().getRect();
    const windowWidth = rect.width;
    const windowHeight = rect.height;

    assert.ok(windowWidth>0);
    assert.ok(windowHeight>0);
  });

  it('Should be able to getWindow position', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');

    // Access each dimension individually
    const { x, y } = await driver.manage().window().getRect();

    // Or store the dimensions and query them later
    const rect = await driver.manage().window().getRect();
    const x1 = rect.x;
    const y1 = rect.y;

    assert.ok(x1>=0);
    assert.ok(y1>=0);
  });
});
import com.oracle.tools.packager.IOUtils.copyFile
import org.openqa.selenium.*
import org.openqa.selenium.chrome.ChromeDriver
import java.io.File

fun main(){
    val driver =  ChromeDriver()
    driver.get("https://www.example.com")
    val scrFile = (driver as TakesScreenshot).getScreenshotAs<File>(OutputType.FILE)
    copyFile(scrFile, File("./image.png"))
    driver.quit()
}
   

TakeElementScreenshot

Usado para capturar a imagem de um elemento para o contexto de navegação atual. O endpoint WebDriver screenshot retorna a captura de tela codificada no formato Base64.

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
import java.io.IOException;

public class SeleniumelementTakeScreenshot {
  public static void main(String args[]) throws IOException {
    WebDriver driver = new ChromeDriver();
    driver.get("https://www.example.com");
    WebElement element = driver.findElement(By.cssSelector("h1"));
    File scrFile = element.getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(scrFile, new File("./image.png"));
    driver.quit();
  }
}
  
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

    # Navigate to url
driver.get("http://www.example.com")

ele = driver.find_element(By.CSS_SELECTOR, 'h1')

    # Returns and base64 encoded string into image
ele.screenshot('./image.png')

driver.quit()
  
    using OpenQA.Selenium;
    using OpenQA.Selenium.Chrome;
    using OpenQA.Selenium.Support.UI;

    // Webdriver
    var driver = new ChromeDriver();
    driver.Navigate().GoToUrl("http://www.example.com");

    // Fetch element using FindElement
    var webElement = driver.FindElement(By.CssSelector("h1"));

    // Screenshot for the element
    var elementScreenshot = (webElement as ITakesScreenshot).GetScreenshot();
    elementScreenshot.SaveAsFile("screenshot_of_element.png");
  
    # Works with Selenium4-alpha7 Ruby bindings and above
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :chrome

begin
  driver.get 'https://example.com/'
  ele = driver.find_element(:css, 'h1')

      # Takes and Stores the element screenshot in specified path
  ele.save_screenshot('./image.jpg')
end
  
    let header = await driver.findElement(By.css('h1'));
      // Captures the element screenshot
      let encodedString = await header.takeScreenshot(true);
      // save screenshot as below
      // await fs.writeFileSync('./image.png', encodedString, 'base64');
  
Show full example
const {Builder, By} = require('selenium-webdriver');
  const chrome = require('selenium-webdriver/chrome');
  const assert = require("node:assert");
  let opts = new chrome.Options();
  opts.addArguments('--headless');
  let startIndex = 0
  let endIndex = 5
  let pdfMagicNumber = 'JVBER'
  let imgMagicNumber = 'iVBOR'
  let base64Code
  
  describe('Interactions - Windows', function () {
    let driver;
    before(async function () {
      driver = await new Builder().forBrowser('chrome').setChromeOptions(opts).build();
    });
  
    after(async () => await driver.quit());
  
    it('Should be able to print page to pdf', async function () {
  
      await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
      let base64 = await driver.printPage({pageRanges: ["1-2"]});
      // page can be saved as a PDF as below
      // await fs.writeFileSync('./test.pdf', base64, 'base64');
  
      base64Code = base64.slice(startIndex, endIndex)
      assert.strictEqual(base64Code, pdfMagicNumber)
    });
  
    it('Should be able to get text using executeScript', async function () {
      await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');
      // Stores the header element
      let header = await driver.findElement(By.css('h1'));
  
      // Executing JavaScript to capture innerText of header element
      let text = await driver.executeScript('return arguments[0].innerText', header);
      assert.strictEqual(text, `Type Stuff`)
    });
  
    it('Should be able to take Element Screenshot', async function () {
      await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');
  
      let header = await driver.findElement(By.css('h1'));
      // Captures the element screenshot
      let encodedString = await header.takeScreenshot(true);
      // save screenshot as below
      // await fs.writeFileSync('./image.png', encodedString, 'base64');
      base64Code = encodedString.slice(startIndex, endIndex)
      assert.strictEqual(base64Code, imgMagicNumber)
    });
  
    it('Should be able to takeScreenshot', async function () {
      await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');
  
      // Captures the screenshot
      let encodedString = await driver.takeScreenshot();
      // save screenshot as below
      // await fs.writeFileSync('./image.png', encodedString, 'base64');
      base64Code = encodedString.slice(startIndex, endIndex)
      assert.strictEqual(base64Code, imgMagicNumber)
    });
  
    it('Should be able to switch to newWindow and newTab and close', async function () {
      await driver.get('https://www.selenium.dev/selenium/web/');
      const initialWindow = await driver.getAllWindowHandles();
      assert.strictEqual(initialWindow.length, 1)
  
      // Opens a new tab and switches to new tab
      await driver.switchTo().newWindow('tab');
      const browserTabs = await driver.getAllWindowHandles();
      assert.strictEqual(browserTabs.length, 2)
  
      // Opens a new window and switches to new window
      await driver.switchTo().newWindow('window');
      const windows = await driver.getAllWindowHandles();
      assert.strictEqual(windows.length, 3)
  
      //Close the tab or window
      await driver.close();
  
      //Switch back to the old tab or window
      await driver.switchTo().window(windows[1]);
  
      const windowsAfterClose = await driver.getAllWindowHandles();
      assert.strictEqual(windowsAfterClose.length, 2);
    });
  
    it('Should be able to getWindow Size', async function () {
      await driver.get('https://www.selenium.dev/selenium/web/');
  
      // Access each dimension individually
      const { width, height } = await driver.manage().window().getRect();
  
      // Or store the dimensions and query them later
      const rect = await driver.manage().window().getRect();
      const windowWidth = rect.width;
      const windowHeight = rect.height;
  
      assert.ok(windowWidth>0);
      assert.ok(windowHeight>0);
    });
  
    it('Should be able to getWindow position', async function () {
      await driver.get('https://www.selenium.dev/selenium/web/');
  
      // Access each dimension individually
      const { x, y } = await driver.manage().window().getRect();
  
      // Or store the dimensions and query them later
      const rect = await driver.manage().window().getRect();
      const x1 = rect.x;
      const y1 = rect.y;
  
      assert.ok(x1>=0);
      assert.ok(y1>=0);
    });
  });
import org.apache.commons.io.FileUtils
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.*
import java.io.File

fun main() {
    val driver = ChromeDriver()
    driver.get("https://www.example.com")
    val element = driver.findElement(By.cssSelector("h1"))
    val scrFile: File = element.getScreenshotAs(OutputType.FILE)
    FileUtils.copyFile(scrFile, File("./image.png"))
    driver.quit()
}
  

Executar Script

Executa o snippet de código JavaScript no contexto atual de um frame ou janela selecionada.

    //Creating the JavascriptExecutor interface object by Type casting
      JavascriptExecutor js = (JavascriptExecutor)driver;
    //Button Element
      WebElement button =driver.findElement(By.name("btnLogin"));
    //Executing JavaScript to click on element
      js.executeScript("arguments[0].click();", button);
    //Get return value from script
      String text = (String) js.executeScript("return arguments[0].innerText", button);
    //Executing JavaScript directly
      js.executeScript("console.log('hello world')");
  
    # Stores the header element
header = driver.find_element(By.CSS_SELECTOR, "h1")

    # Executing JavaScript to capture innerText of header element
driver.execute_script('return arguments[0].innerText', header)
  
   //creating Chromedriver instance
	IWebDriver driver = new ChromeDriver();
	//Creating the JavascriptExecutor interface object by Type casting
	IJavaScriptExecutor js = (IJavaScriptExecutor) driver;
	//Button Element
	IWebElement button = driver.FindElement(By.Name("btnLogin"));
	//Executing JavaScript to click on element
	js.ExecuteScript("arguments[0].click();", button);
	//Get return value from script
	String text = (String)js.ExecuteScript("return arguments[0].innerText", button);
	//Executing JavaScript directly
	js.ExecuteScript("console.log('hello world')");
  
    # Stores the header element
header = driver.find_element(css: 'h1')

    # Get return value from script
result = driver.execute_script("return arguments[0].innerText", header)

    # Executing JavaScript directly
driver.execute_script("alert('hello world')")
  
    // Stores the header element
    let header = await driver.findElement(By.css('h1'));

    // Executing JavaScript to capture innerText of header element
    let text = await driver.executeScript('return arguments[0].innerText', header);
Show full example
const {Builder, By} = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
const assert = require("node:assert");
let opts = new chrome.Options();
opts.addArguments('--headless');
let startIndex = 0
let endIndex = 5
let pdfMagicNumber = 'JVBER'
let imgMagicNumber = 'iVBOR'
let base64Code

describe('Interactions - Windows', function () {
  let driver;
  before(async function () {
    driver = await new Builder().forBrowser('chrome').setChromeOptions(opts).build();
  });

  after(async () => await driver.quit());

  it('Should be able to print page to pdf', async function () {

    await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
    let base64 = await driver.printPage({pageRanges: ["1-2"]});
    // page can be saved as a PDF as below
    // await fs.writeFileSync('./test.pdf', base64, 'base64');

    base64Code = base64.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, pdfMagicNumber)
  });

  it('Should be able to get text using executeScript', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');
    // Stores the header element
    let header = await driver.findElement(By.css('h1'));

    // Executing JavaScript to capture innerText of header element
    let text = await driver.executeScript('return arguments[0].innerText', header);
    assert.strictEqual(text, `Type Stuff`)
  });

  it('Should be able to take Element Screenshot', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');

    let header = await driver.findElement(By.css('h1'));
    // Captures the element screenshot
    let encodedString = await header.takeScreenshot(true);
    // save screenshot as below
    // await fs.writeFileSync('./image.png', encodedString, 'base64');
    base64Code = encodedString.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, imgMagicNumber)
  });

  it('Should be able to takeScreenshot', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');

    // Captures the screenshot
    let encodedString = await driver.takeScreenshot();
    // save screenshot as below
    // await fs.writeFileSync('./image.png', encodedString, 'base64');
    base64Code = encodedString.slice(startIndex, endIndex)
    assert.strictEqual(base64Code, imgMagicNumber)
  });

  it('Should be able to switch to newWindow and newTab and close', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');
    const initialWindow = await driver.getAllWindowHandles();
    assert.strictEqual(initialWindow.length, 1)

    // Opens a new tab and switches to new tab
    await driver.switchTo().newWindow('tab');
    const browserTabs = await driver.getAllWindowHandles();
    assert.strictEqual(browserTabs.length, 2)

    // Opens a new window and switches to new window
    await driver.switchTo().newWindow('window');
    const windows = await driver.getAllWindowHandles();
    assert.strictEqual(windows.length, 3)

    //Close the tab or window
    await driver.close();

    //Switch back to the old tab or window
    await driver.switchTo().window(windows[1]);

    const windowsAfterClose = await driver.getAllWindowHandles();
    assert.strictEqual(windowsAfterClose.length, 2);
  });

  it('Should be able to getWindow Size', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');

    // Access each dimension individually
    const { width, height } = await driver.manage().window().getRect();

    // Or store the dimensions and query them later
    const rect = await driver.manage().window().getRect();
    const windowWidth = rect.width;
    const windowHeight = rect.height;

    assert.ok(windowWidth>0);
    assert.ok(windowHeight>0);
  });

  it('Should be able to getWindow position', async function () {
    await driver.get('https://www.selenium.dev/selenium/web/');

    // Access each dimension individually
    const { x, y } = await driver.manage().window().getRect();

    // Or store the dimensions and query them later
    const rect = await driver.manage().window().getRect();
    const x1 = rect.x;
    const y1 = rect.y;

    assert.ok(x1>=0);
    assert.ok(y1>=0);
  });
});
// Stores the header element
val header = driver.findElement(By.cssSelector("h1"))

// Get return value from script
val result = driver.executeScript("return arguments[0].innerText", header)

// Executing JavaScript directly
driver.executeScript("alert('hello world')")
  

Imprimir Página

Imprime a página atual dentro do navegador

Nota: isto requer que navegadores Chromium estejam no modo sem cabeçalho

    import org.openqa.selenium.print.PrintOptions;

    driver.get("https://www.selenium.dev");
    printer = (PrintsPage) driver;

    PrintOptions printOptions = new PrintOptions();
    printOptions.setPageRanges("1-2");

    Pdf pdf = printer.print(printOptions);
    String content = pdf.getContent();
  
    from selenium.webdriver.common.print_page_options import PrintOptions

    print_options = PrintOptions()
    print_options.page_ranges = ['1-2']

    driver.get("printPage.html")

    base64code = driver.print_page(print_options)
  
    // code sample not available please raise a PR
  
    driver.navigate_to 'https://www.selenium.dev'

    base64encodedContent = driver.print_page(orientation: 'landscape')
  
    await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
      let base64 = await driver.printPage({pageRanges: ["1-2"]});
      // page can be saved as a PDF as below
      // await fs.writeFileSync('./test.pdf', base64, 'base64');
  
Show full example
const {Builder, By} = require('selenium-webdriver');
  const chrome = require('selenium-webdriver/chrome');
  const assert = require("node:assert");
  let opts = new chrome.Options();
  opts.addArguments('--headless');
  let startIndex = 0
  let endIndex = 5
  let pdfMagicNumber = 'JVBER'
  let imgMagicNumber = 'iVBOR'
  let base64Code
  
  describe('Interactions - Windows', function () {
    let driver;
    before(async function () {
      driver = await new Builder().forBrowser('chrome').setChromeOptions(opts).build();
    });
  
    after(async () => await driver.quit());
  
    it('Should be able to print page to pdf', async function () {
  
      await driver.get('https://www.selenium.dev/selenium/web/alerts.html');
      let base64 = await driver.printPage({pageRanges: ["1-2"]});
      // page can be saved as a PDF as below
      // await fs.writeFileSync('./test.pdf', base64, 'base64');
  
      base64Code = base64.slice(startIndex, endIndex)
      assert.strictEqual(base64Code, pdfMagicNumber)
    });
  
    it('Should be able to get text using executeScript', async function () {
      await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');
      // Stores the header element
      let header = await driver.findElement(By.css('h1'));
  
      // Executing JavaScript to capture innerText of header element
      let text = await driver.executeScript('return arguments[0].innerText', header);
      assert.strictEqual(text, `Type Stuff`)
    });
  
    it('Should be able to take Element Screenshot', async function () {
      await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');
  
      let header = await driver.findElement(By.css('h1'));
      // Captures the element screenshot
      let encodedString = await header.takeScreenshot(true);
      // save screenshot as below
      // await fs.writeFileSync('./image.png', encodedString, 'base64');
      base64Code = encodedString.slice(startIndex, endIndex)
      assert.strictEqual(base64Code, imgMagicNumber)
    });
  
    it('Should be able to takeScreenshot', async function () {
      await driver.get('https://www.selenium.dev/selenium/web/javascriptPage.html');
  
      // Captures the screenshot
      let encodedString = await driver.takeScreenshot();
      // save screenshot as below
      // await fs.writeFileSync('./image.png', encodedString, 'base64');
      base64Code = encodedString.slice(startIndex, endIndex)
      assert.strictEqual(base64Code, imgMagicNumber)
    });
  
    it('Should be able to switch to newWindow and newTab and close', async function () {
      await driver.get('https://www.selenium.dev/selenium/web/');
      const initialWindow = await driver.getAllWindowHandles();
      assert.strictEqual(initialWindow.length, 1)
  
      // Opens a new tab and switches to new tab
      await driver.switchTo().newWindow('tab');
      const browserTabs = await driver.getAllWindowHandles();
      assert.strictEqual(browserTabs.length, 2)
  
      // Opens a new window and switches to new window
      await driver.switchTo().newWindow('window');
      const windows = await driver.getAllWindowHandles();
      assert.strictEqual(windows.length, 3)
  
      //Close the tab or window
      await driver.close();
  
      //Switch back to the old tab or window
      await driver.switchTo().window(windows[1]);
  
      const windowsAfterClose = await driver.getAllWindowHandles();
      assert.strictEqual(windowsAfterClose.length, 2);
    });
  
    it('Should be able to getWindow Size', async function () {
      await driver.get('https://www.selenium.dev/selenium/web/');
  
      // Access each dimension individually
      const { width, height } = await driver.manage().window().getRect();
  
      // Or store the dimensions and query them later
      const rect = await driver.manage().window().getRect();
      const windowWidth = rect.width;
      const windowHeight = rect.height;
  
      assert.ok(windowWidth>0);
      assert.ok(windowHeight>0);
    });
  
    it('Should be able to getWindow position', async function () {
      await driver.get('https://www.selenium.dev/selenium/web/');
  
      // Access each dimension individually
      const { x, y } = await driver.manage().window().getRect();
  
      // Or store the dimensions and query them later
      const rect = await driver.manage().window().getRect();
      const x1 = rect.x;
      const y1 = rect.y;
  
      assert.ok(x1>=0);
      assert.ok(y1>=0);
    });
  });
    driver.get("https://www.selenium.dev")
    val printer = driver as PrintsPage

    val printOptions = PrintOptions()
    printOptions.setPageRanges("1-2")
    
    val pdf: Pdf = printer.print(printOptions)
    val content = pdf.content
  

7 - Virtual Authenticator

Uma representação do modelo Web Authenticator.

Aplicações web podem habilitar um mecanismo de autenticação baseado em chaves públicas conhecido como Web Authentication para autenticar usuários sem usar uma senha. Web Authentication define APIs que permitem ao usuário criar uma credencial e registra-la com um autenticador. Um autenticador pode ser um dispositivo ou um software que guarde as chaves públicas do usuário e as acesse caso seja pedido.

Como o nome sugere, Virtual Authenticator emula esses autenticadores para testes.

Virtual Authenticator Options

Um Autenticador Virtual tem uma série de propriedades. Essas propriedades são mapeadas como VirtualAuthenticatorOptions nos bindings do Selenium.

    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true)
      .setHasUserVerification(true)
      .setIsUserConsenting(true)
      .setTransport(VirtualAuthenticatorOptions.Transport.USB)
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);
Show full example
package dev.selenium.interactions;

import dev.selenium.BaseChromeTest;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.InvalidArgumentException;
import org.openqa.selenium.virtualauthenticator.Credential;
import org.openqa.selenium.virtualauthenticator.HasVirtualAuthenticator;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticator;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;

public class VirtualAuthenticatorTest extends BaseChromeTest {

  /**
   * A pkcs#8 encoded encrypted RSA private key as a base64url string.
   */
  private final static String
    base64EncodedRsaPK =
    "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"
    + "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"
    + "GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"
    + "9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"
    + "vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"
    + "zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"
    + "XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"
    + "RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"
    + "QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"
    + "S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"
    + "ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"
    + "ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"
    + "OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"
    + "ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"
    + "hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"
    + "WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"
    + "NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"
    + "nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";

  private final static PKCS8EncodedKeySpec rsaPrivateKey =
    new PKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(base64EncodedRsaPK));

  // A pkcs#8 encoded unencrypted EC256 private key as a base64url string.
  String base64EncodedEC256PK =
    "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"
    + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"
    + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";

  PKCS8EncodedKeySpec ec256PrivateKey =
    new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));

  @Test
  public void testVirtualOptions() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true)
      .setHasUserVerification(true)
      .setIsUserConsenting(true)
      .setTransport(VirtualAuthenticatorOptions.Transport.USB)
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    Assertions.assertEquals(6, options.toMap().size());
  }

  @Test
  public void testCreateAuthenticator() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    List<Credential> credentialList = authenticator.getCredentials();

    Assertions.assertEquals(0, credentialList.size());
  }

  @Test
  public void testRemoveAuthenticator() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions();
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    ((HasVirtualAuthenticator) driver).removeVirtualAuthenticator(authenticator);

    Assertions.assertThrows(InvalidArgumentException.class, authenticator::getCredentials);
  }

  @Test
  public void testCreateAndAddResidentialKey() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasResidentKey(true)
      .setHasUserVerification(true)
      .setIsUserVerified(true);
    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
  }

  @Test
  public void testAddResidentCredentialNotSupportedWhenAuthenticatorUsesU2FProtocol() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(true);

    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    PKCS8EncodedKeySpec privateKey =
      new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential credential = Credential.createResidentCredential(
      credentialId, "localhost", privateKey, userHandle, /*signCount=*/0);

    Assertions.assertThrows(InvalidArgumentException.class,
                            () -> authenticator.addCredential(credential));
  }


  @Test
  public void testCreateAndAddNonResidentialKey() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    Credential nonResidentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", ec256PrivateKey, /*signCount=*/0);
    authenticator.addCredential(nonResidentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
  }

  @Test
  public void testGetCredential() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasResidentKey(true)
      .setHasUserVerification(true)
      .setIsUserVerified(true);
    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
    Assertions.assertArrayEquals(rsaPrivateKey.getEncoded(), credential.getPrivateKey().getEncoded());
  }

  @Test
  public void testRemoveCredential() {
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential credential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, 0);

    authenticator.addCredential(credential);

    authenticator.removeCredential(credentialId);
    Assertions.assertEquals(0, authenticator.getCredentials().size());
  }

  @Test
  public void testRemoveAllCredentials() {
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential residentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    authenticator.removeAllCredentials();
    Assertions.assertEquals(0, authenticator.getCredentials().size());
  }

  @Test
  public void testSetUserVerified() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true);

    Assertions.assertTrue((boolean) options.toMap().get("isUserVerified"));
  }
}
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true)
                .SetHasUserVerification(true)
                .SetIsUserConsenting(true)
                .SetTransport(VirtualAuthenticatorOptions.Transport.USB)
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);
Show full example
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.IdentityModel.Tokens;
using OpenQA.Selenium;
using OpenQA.Selenium.VirtualAuth;
using static OpenQA.Selenium.VirtualAuth.VirtualAuthenticatorOptions;
using System.Collections.Generic;
using System;

namespace SeleniumDocs.VirtualAuthentication
{
    [TestClass]
    public class VirtualAuthenticatorTest : BaseChromeTest
    {
        //A pkcs#8 encoded encrypted RSA private key as a base64 string.
        private static string base64EncodedRSAPK =
                "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"
              + "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"
              + "GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"
              + "9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"
              + "vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"
              + "zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"
              + "XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"
              + "RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"
              + "QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"
              + "S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"
              + "ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"
              + "ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"
              + "OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"
              + "ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"
              + "hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"
              + "WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"
              + "NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"
              + "nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";

        private static byte[] bytes = System.Convert.FromBase64String(base64EncodedRSAPK);
        private string base64EncodedPK = Base64UrlEncoder.Encode(bytes);

        // A pkcs#8 encoded unencrypted EC256 private key as a base64url string.
        private string base64EncodedEC256PK =
              "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"
              + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"
              + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";


        [TestMethod]
        public void VirtualOptionsShouldAllowSettingOptions()
        {
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true)
                .SetHasUserVerification(true)
                .SetIsUserConsenting(true)
                .SetTransport(VirtualAuthenticatorOptions.Transport.USB)
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            Assert.AreEqual(6, options.ToDictionary().Count);
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAuthenticator()
        {
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            // Register a virtual authenticator
            ((WebDriver)driver).AddVirtualAuthenticator(options);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();

            Assert.AreEqual(0, credentialList.Count);
        }


        [TestMethod]
        public void ShouldBeAbleToRemoveAuthenticator()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            String virtualAuthenticatorId = ((WebDriver)driver).AddVirtualAuthenticator(options);

            ((WebDriver)driver).RemoveVirtualAuthenticator(virtualAuthenticatorId);

            // Since the authenticator was removed, any operation using it will throw an error
            Assert.ThrowsException<InvalidOperationException>(() => ((WebDriver)driver).GetCredentials());
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAndAddResidentialKey()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(Protocol.CTAP2)
                .SetHasResidentKey(true)
                .SetHasUserVerification(true)
                .SetIsUserVerified(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);

            ((WebDriver)driver).AddCredential(residentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, credential.Id);
        }

        [TestMethod]
        public void ShouldNotAddResidentCredentialWhenAuthenticatorUsesU2FProtocol()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential credential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, userHandle, 0);

            Assert.ThrowsException<WebDriverArgumentException>(() => ((WebDriver)driver).AddCredential(credential));
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAndAddNonResidentKey()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, nonResidentCredential.Id);
        }

        [TestMethod]
        public void ShouldBeAbleToGetCredential()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(Protocol.CTAP2)
                .SetHasResidentKey(true)
                .SetHasUserVerification(true)
                .SetIsUserVerified(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);

            ((WebDriver)driver).AddCredential(residentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, residentCredential.Id);
            Assert.AreEqual(base64EncodedPK, credential.PrivateKey);
        }

        [TestMethod]
        public void ShouldBeAbleToRemoveCredential()
        {
            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveCredential(credentialId);

            Assert.AreEqual(0, ((WebDriver)driver).GetCredentials().Count);
        }


        [TestMethod]
        public void ShouldBeAbleToRemoveAllCredentias()
        {
            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveAllCredentials();

            Assert.AreEqual(0, ((WebDriver)driver).GetCredentials().Count);
        }

        [TestMethod]
        public void ShouldBeSetVerifiedOption()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true);

            Assert.IsTrue((bool)options.ToDictionary()["isUserVerified"]);
        }
    }
}
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True
    options.has_user_verification = True
    options.is_user_consenting = True
    options.transport = VirtualAuthenticatorOptions.Transport.USB
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False
Show full example
import pytest
from base64 import urlsafe_b64decode, urlsafe_b64encode

from selenium.common.exceptions import InvalidArgumentException
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.virtual_authenticator import (
    Credential,
    VirtualAuthenticatorOptions,
)


BASE64__ENCODED_PK = '''
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV
oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ
FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq
GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0
+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM
8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD
/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ
5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe
pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol
L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d
xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi
uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8
K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct
lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa
9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
'''


@pytest.fixture(scope="module", autouse=True)
def driver():
    yield WebDriver()


def test_virtual_authenticator_options():
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True
    options.has_user_verification = True
    options.is_user_consenting = True
    options.transport = VirtualAuthenticatorOptions.Transport.USB
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    assert len(options.to_dict()) == 6


def test_add_authenticator(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # Get list of credentials
    credential_list = driver.get_credentials()

    assert len(credential_list) == 0


def test_remove_authenticator(driver):
    # Create default virtual authenticator option
    options = VirtualAuthenticatorOptions()

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # Remove virtual authenticator
    driver.remove_virtual_authenticator()
    assert driver.virtual_authenticator_id is None


def test_create_and_add_resident_key(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
    options.has_resident_key = True
    options.has_user_verification = True
    options.is_user_verified = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(resident_credential)

    # get list of all the registered credentials 
    credential_list = driver.get_credentials()
    assert len(credential_list) == 1


def test_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a  resident credential using above parameters
    credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)

    # Expect InvalidArgumentException 
    with pytest.raises(InvalidArgumentException):
        driver.add_credential(credential)


def test_create_and_add_non_resident_key(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Non Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a non resident credential using above parameters
    credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(credential)
    
    # get list of all the registered credentials 
    credential_list = driver.get_credentials()
    assert len(credential_list) == 1



def test_get_credential(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
    options.has_resident_key = True
    options.has_user_verfied = True
    options.is_user_verified = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)
    
    # add the credential created to virtual authenticator
    driver.add_credential(credential)

    # get list of all the registered credentials 
    credential_list = driver.get_credentials()

    assert len(credential_list) == 1
    assert credential_list[0].id == urlsafe_b64encode(credential_id).decode()


def test_remove_credential(driver):
    # Create default virtual authenticator options
    options = VirtualAuthenticatorOptions()

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Non Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a non resident credential using above parameters
    credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(credential)

    # remove the credential created from virtual authenticator
    driver.remove_credential(credential.id)

    # credential can also be removed using Byte Array
    # driver.remove_credential(credential_id) 

    assert len(driver.get_credentials()) == 0


def test_remove_all_credentials(driver):
    # Create default virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.has_resident_key = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)
    
    # add the credential created to virtual authenticator
    driver.add_credential(resident_credential)

    # remove all credentials in virtual authenticator
    driver.remove_all_credentials()

    assert len(driver.get_credentials()) == 0


def test_set_user_verified():
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True

    assert options.to_dict().get("isUserVerified") is True
    options.setHasUserVerification(true);
    options.setIsUserConsenting(true);
    options.setTransport(Transport['USB']);
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(false);

    assert(Object.keys(options).length === 6);
Show full example
const {VirtualAuthenticatorOptions, Transport, Protocol} = require("selenium-webdriver/lib/virtual_authenticator");
const assert = require('assert')


describe('Virtual authenticator options', function () {
  let options;

  it('Virtual options', async function () {
    options = new VirtualAuthenticatorOptions();
    options.setIsUserVerified(true);
    options.setHasUserVerification(true);
    options.setIsUserConsenting(true);
    options.setTransport(Transport['USB']);
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(false);

    assert(Object.keys(options).length === 6);
  });

  it('User verified', async function () {
    options.setIsUserVerified(true);

    assert(options.toDict()['isUserVerified']);
  });
});

Add Virtual Authenticator

Cria um novo autenticador virtual com as propriedades fornecidas.

    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);
Show full example
package dev.selenium.interactions;

import dev.selenium.BaseChromeTest;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.InvalidArgumentException;
import org.openqa.selenium.virtualauthenticator.Credential;
import org.openqa.selenium.virtualauthenticator.HasVirtualAuthenticator;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticator;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;

public class VirtualAuthenticatorTest extends BaseChromeTest {

  /**
   * A pkcs#8 encoded encrypted RSA private key as a base64url string.
   */
  private final static String
    base64EncodedRsaPK =
    "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"
    + "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"
    + "GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"
    + "9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"
    + "vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"
    + "zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"
    + "XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"
    + "RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"
    + "QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"
    + "S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"
    + "ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"
    + "ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"
    + "OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"
    + "ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"
    + "hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"
    + "WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"
    + "NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"
    + "nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";

  private final static PKCS8EncodedKeySpec rsaPrivateKey =
    new PKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(base64EncodedRsaPK));

  // A pkcs#8 encoded unencrypted EC256 private key as a base64url string.
  String base64EncodedEC256PK =
    "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"
    + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"
    + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";

  PKCS8EncodedKeySpec ec256PrivateKey =
    new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));

  @Test
  public void testVirtualOptions() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true)
      .setHasUserVerification(true)
      .setIsUserConsenting(true)
      .setTransport(VirtualAuthenticatorOptions.Transport.USB)
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    Assertions.assertEquals(6, options.toMap().size());
  }

  @Test
  public void testCreateAuthenticator() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    List<Credential> credentialList = authenticator.getCredentials();

    Assertions.assertEquals(0, credentialList.size());
  }

  @Test
  public void testRemoveAuthenticator() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions();
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    ((HasVirtualAuthenticator) driver).removeVirtualAuthenticator(authenticator);

    Assertions.assertThrows(InvalidArgumentException.class, authenticator::getCredentials);
  }

  @Test
  public void testCreateAndAddResidentialKey() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasResidentKey(true)
      .setHasUserVerification(true)
      .setIsUserVerified(true);
    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
  }

  @Test
  public void testAddResidentCredentialNotSupportedWhenAuthenticatorUsesU2FProtocol() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(true);

    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    PKCS8EncodedKeySpec privateKey =
      new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential credential = Credential.createResidentCredential(
      credentialId, "localhost", privateKey, userHandle, /*signCount=*/0);

    Assertions.assertThrows(InvalidArgumentException.class,
                            () -> authenticator.addCredential(credential));
  }


  @Test
  public void testCreateAndAddNonResidentialKey() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    Credential nonResidentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", ec256PrivateKey, /*signCount=*/0);
    authenticator.addCredential(nonResidentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
  }

  @Test
  public void testGetCredential() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasResidentKey(true)
      .setHasUserVerification(true)
      .setIsUserVerified(true);
    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
    Assertions.assertArrayEquals(rsaPrivateKey.getEncoded(), credential.getPrivateKey().getEncoded());
  }

  @Test
  public void testRemoveCredential() {
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential credential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, 0);

    authenticator.addCredential(credential);

    authenticator.removeCredential(credentialId);
    Assertions.assertEquals(0, authenticator.getCredentials().size());
  }

  @Test
  public void testRemoveAllCredentials() {
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential residentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    authenticator.removeAllCredentials();
    Assertions.assertEquals(0, authenticator.getCredentials().size());
  }

  @Test
  public void testSetUserVerified() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true);

    Assertions.assertTrue((boolean) options.toMap().get("isUserVerified"));
  }
}
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            // Register a virtual authenticator
            ((WebDriver)driver).AddVirtualAuthenticator(options);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
Show full example
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.IdentityModel.Tokens;
using OpenQA.Selenium;
using OpenQA.Selenium.VirtualAuth;
using static OpenQA.Selenium.VirtualAuth.VirtualAuthenticatorOptions;
using System.Collections.Generic;
using System;

namespace SeleniumDocs.VirtualAuthentication
{
    [TestClass]
    public class VirtualAuthenticatorTest : BaseChromeTest
    {
        //A pkcs#8 encoded encrypted RSA private key as a base64 string.
        private static string base64EncodedRSAPK =
                "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"
              + "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"
              + "GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"
              + "9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"
              + "vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"
              + "zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"
              + "XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"
              + "RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"
              + "QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"
              + "S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"
              + "ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"
              + "ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"
              + "OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"
              + "ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"
              + "hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"
              + "WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"
              + "NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"
              + "nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";

        private static byte[] bytes = System.Convert.FromBase64String(base64EncodedRSAPK);
        private string base64EncodedPK = Base64UrlEncoder.Encode(bytes);

        // A pkcs#8 encoded unencrypted EC256 private key as a base64url string.
        private string base64EncodedEC256PK =
              "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"
              + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"
              + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";


        [TestMethod]
        public void VirtualOptionsShouldAllowSettingOptions()
        {
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true)
                .SetHasUserVerification(true)
                .SetIsUserConsenting(true)
                .SetTransport(VirtualAuthenticatorOptions.Transport.USB)
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            Assert.AreEqual(6, options.ToDictionary().Count);
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAuthenticator()
        {
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            // Register a virtual authenticator
            ((WebDriver)driver).AddVirtualAuthenticator(options);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();

            Assert.AreEqual(0, credentialList.Count);
        }


        [TestMethod]
        public void ShouldBeAbleToRemoveAuthenticator()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            String virtualAuthenticatorId = ((WebDriver)driver).AddVirtualAuthenticator(options);

            ((WebDriver)driver).RemoveVirtualAuthenticator(virtualAuthenticatorId);

            // Since the authenticator was removed, any operation using it will throw an error
            Assert.ThrowsException<InvalidOperationException>(() => ((WebDriver)driver).GetCredentials());
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAndAddResidentialKey()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(Protocol.CTAP2)
                .SetHasResidentKey(true)
                .SetHasUserVerification(true)
                .SetIsUserVerified(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);

            ((WebDriver)driver).AddCredential(residentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, credential.Id);
        }

        [TestMethod]
        public void ShouldNotAddResidentCredentialWhenAuthenticatorUsesU2FProtocol()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential credential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, userHandle, 0);

            Assert.ThrowsException<WebDriverArgumentException>(() => ((WebDriver)driver).AddCredential(credential));
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAndAddNonResidentKey()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, nonResidentCredential.Id);
        }

        [TestMethod]
        public void ShouldBeAbleToGetCredential()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(Protocol.CTAP2)
                .SetHasResidentKey(true)
                .SetHasUserVerification(true)
                .SetIsUserVerified(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);

            ((WebDriver)driver).AddCredential(residentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, residentCredential.Id);
            Assert.AreEqual(base64EncodedPK, credential.PrivateKey);
        }

        [TestMethod]
        public void ShouldBeAbleToRemoveCredential()
        {
            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveCredential(credentialId);

            Assert.AreEqual(0, ((WebDriver)driver).GetCredentials().Count);
        }


        [TestMethod]
        public void ShouldBeAbleToRemoveAllCredentias()
        {
            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveAllCredentials();

            Assert.AreEqual(0, ((WebDriver)driver).GetCredentials().Count);
        }

        [TestMethod]
        public void ShouldBeSetVerifiedOption()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true);

            Assert.IsTrue((bool)options.ToDictionary()["isUserVerified"]);
        }
    }
}
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)
Show full example
import pytest
from base64 import urlsafe_b64decode, urlsafe_b64encode

from selenium.common.exceptions import InvalidArgumentException
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.virtual_authenticator import (
    Credential,
    VirtualAuthenticatorOptions,
)


BASE64__ENCODED_PK = '''
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV
oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ
FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq
GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0
+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM
8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD
/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ
5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe
pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol
L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d
xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi
uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8
K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct
lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa
9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
'''


@pytest.fixture(scope="module", autouse=True)
def driver():
    yield WebDriver()


def test_virtual_authenticator_options():
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True
    options.has_user_verification = True
    options.is_user_consenting = True
    options.transport = VirtualAuthenticatorOptions.Transport.USB
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    assert len(options.to_dict()) == 6


def test_add_authenticator(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # Get list of credentials
    credential_list = driver.get_credentials()

    assert len(credential_list) == 0


def test_remove_authenticator(driver):
    # Create default virtual authenticator option
    options = VirtualAuthenticatorOptions()

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # Remove virtual authenticator
    driver.remove_virtual_authenticator()
    assert driver.virtual_authenticator_id is None


def test_create_and_add_resident_key(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
    options.has_resident_key = True
    options.has_user_verification = True
    options.is_user_verified = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(resident_credential)

    # get list of all the registered credentials 
    credential_list = driver.get_credentials()
    assert len(credential_list) == 1


def test_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a  resident credential using above parameters
    credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)

    # Expect InvalidArgumentException 
    with pytest.raises(InvalidArgumentException):
        driver.add_credential(credential)


def test_create_and_add_non_resident_key(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Non Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a non resident credential using above parameters
    credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(credential)
    
    # get list of all the registered credentials 
    credential_list = driver.get_credentials()
    assert len(credential_list) == 1



def test_get_credential(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
    options.has_resident_key = True
    options.has_user_verfied = True
    options.is_user_verified = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)
    
    # add the credential created to virtual authenticator
    driver.add_credential(credential)

    # get list of all the registered credentials 
    credential_list = driver.get_credentials()

    assert len(credential_list) == 1
    assert credential_list[0].id == urlsafe_b64encode(credential_id).decode()


def test_remove_credential(driver):
    # Create default virtual authenticator options
    options = VirtualAuthenticatorOptions()

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Non Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a non resident credential using above parameters
    credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(credential)

    # remove the credential created from virtual authenticator
    driver.remove_credential(credential.id)

    # credential can also be removed using Byte Array
    # driver.remove_credential(credential_id) 

    assert len(driver.get_credentials()) == 0


def test_remove_all_credentials(driver):
    # Create default virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.has_resident_key = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)
    
    # add the credential created to virtual authenticator
    driver.add_credential(resident_credential)

    # remove all credentials in virtual authenticator
    driver.remove_all_credentials()

    assert len(driver.get_credentials()) == 0


def test_set_user_verified():
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True

    assert options.to_dict().get("isUserVerified") is True
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(false);

    // Register a virtual authenticator
    await driver.addVirtualAuthenticator(options);
Show full example

const { Builder} = require("selenium-webdriver");
const { Credential, VirtualAuthenticatorOptions, Transport, Protocol } = require("selenium-webdriver/lib/virtual_authenticator");
const assert = require('assert')
const { InvalidArgumentError } = require("selenium-webdriver/lib/error");


describe('Virtual authenticator', function() {
  const BASE64_ENCODED_PK =
    "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr" +
    "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV" +
    "oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ" +
    "FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq" +
    "GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0" +
    "+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM" +
    "8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD" +
    "/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ" +
    "5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe" +
    "pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol" +
    "L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d" +
    "xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi" +
    "uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8" +
    "K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct" +
    "lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa" +
    "9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH" +
    "zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H" +
    "BYGpI8g==";

  const base64EncodedPK =
    "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q" +
    "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU" +
    "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";

  let options;
  let driver;

  before(async function() {
    options = new VirtualAuthenticatorOptions();
    driver = await new Builder().forBrowser('chrome').build();
  });

  after(async() => await driver.quit());

  function arraysEqual(array1, array2) {
    return (array1.length === array2.length &&
      array1.every((item) => array2.includes(item)) &&
      array2.every((item) => array1.includes(item)));
  }

  it('Register a virtual authenticator', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(false);

    // Register a virtual authenticator
    await driver.addVirtualAuthenticator(options);
    let credentialList = await driver.getCredentials();

    assert.equal(0, credentialList.length);
  });

  it('Remove authenticator', async function() {
    await driver.addVirtualAuthenticator(options);
    await driver.removeVirtualAuthenticator();

    // Since the authenticator was removed, any operation using it will throw an error
    try {
      await driver.getCredentials()
    }
    catch (e) {
      if (e instanceof InvalidArgumentError) {
        assert(true)
      }
      else {
        assert(false)
      }
    }
  });

  it('Createa and add residential key', async function() {
    options.setProtocol(Protocol['CTAP2']);
    options.setHasResidentKey(true);
    options.setHasUserVerification(true);
    options.setIsUserVerified(true);

    await driver.addVirtualAuthenticator(options);

    let residentCredential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(residentCredential);
    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
  });

  it('Add resident credential not supported when authenticator uses U2F protocol', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(true);

    await driver.addVirtualAuthenticator(options);

    let credential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(base64EncodedPK, 'base64').toString('binary'),
      0);

    try {
      await driver.addCredential(credential)
    }
    catch (e) {
      if (e instanceof InvalidArgumentError) {
        assert(true)
      }
      else {
        assert(false)
      }
    }
  });

  it('Create and add non residential key', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(false);

    await driver.addVirtualAuthenticator(options);

    let nonResidentCredential = new Credential().createNonResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      Buffer.from(base64EncodedPK, 'base64').toString('binary'),
      0);

    await driver.addCredential(nonResidentCredential);

    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
  });

  it('Get credential', async function() {
    options.setProtocol(Protocol['CTAP2']);
    options.setHasResidentKey(true);
    options.setHasUserVerification(true);
    options.setIsUserVerified(true);

    await driver.addVirtualAuthenticator(options);

    let residentCredential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(residentCredential);

    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
    assert.equal(BASE64_ENCODED_PK, Buffer.from(credentialList[0].privateKey(), 'binary').toString('base64'));
  });

  it('Remove all credentials', async function() {
    await driver.addVirtualAuthenticator(options);

    let nonResidentCredential = new Credential().createNonResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(nonResidentCredential);
    await driver.removeAllCredentials();

    let credentialList = await driver.getCredentials();
    assert.equal(0, credentialList.length);
  });

  it('Set is user verified', async function() {
    options.setIsUserVerified(true);
    assert.equal(options.getIsUserVerified(), true);
  });
});

Remove Virtual Authenticator

Remove o autenticador virtual adicionado anteriormente.

    ((HasVirtualAuthenticator) driver).removeVirtualAuthenticator(authenticator);
Show full example
package dev.selenium.interactions;

import dev.selenium.BaseChromeTest;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.InvalidArgumentException;
import org.openqa.selenium.virtualauthenticator.Credential;
import org.openqa.selenium.virtualauthenticator.HasVirtualAuthenticator;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticator;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;

public class VirtualAuthenticatorTest extends BaseChromeTest {

  /**
   * A pkcs#8 encoded encrypted RSA private key as a base64url string.
   */
  private final static String
    base64EncodedRsaPK =
    "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"
    + "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"
    + "GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"
    + "9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"
    + "vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"
    + "zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"
    + "XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"
    + "RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"
    + "QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"
    + "S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"
    + "ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"
    + "ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"
    + "OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"
    + "ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"
    + "hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"
    + "WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"
    + "NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"
    + "nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";

  private final static PKCS8EncodedKeySpec rsaPrivateKey =
    new PKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(base64EncodedRsaPK));

  // A pkcs#8 encoded unencrypted EC256 private key as a base64url string.
  String base64EncodedEC256PK =
    "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"
    + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"
    + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";

  PKCS8EncodedKeySpec ec256PrivateKey =
    new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));

  @Test
  public void testVirtualOptions() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true)
      .setHasUserVerification(true)
      .setIsUserConsenting(true)
      .setTransport(VirtualAuthenticatorOptions.Transport.USB)
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    Assertions.assertEquals(6, options.toMap().size());
  }

  @Test
  public void testCreateAuthenticator() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    List<Credential> credentialList = authenticator.getCredentials();

    Assertions.assertEquals(0, credentialList.size());
  }

  @Test
  public void testRemoveAuthenticator() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions();
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    ((HasVirtualAuthenticator) driver).removeVirtualAuthenticator(authenticator);

    Assertions.assertThrows(InvalidArgumentException.class, authenticator::getCredentials);
  }

  @Test
  public void testCreateAndAddResidentialKey() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasResidentKey(true)
      .setHasUserVerification(true)
      .setIsUserVerified(true);
    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
  }

  @Test
  public void testAddResidentCredentialNotSupportedWhenAuthenticatorUsesU2FProtocol() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(true);

    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    PKCS8EncodedKeySpec privateKey =
      new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential credential = Credential.createResidentCredential(
      credentialId, "localhost", privateKey, userHandle, /*signCount=*/0);

    Assertions.assertThrows(InvalidArgumentException.class,
                            () -> authenticator.addCredential(credential));
  }


  @Test
  public void testCreateAndAddNonResidentialKey() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    Credential nonResidentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", ec256PrivateKey, /*signCount=*/0);
    authenticator.addCredential(nonResidentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
  }

  @Test
  public void testGetCredential() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasResidentKey(true)
      .setHasUserVerification(true)
      .setIsUserVerified(true);
    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
    Assertions.assertArrayEquals(rsaPrivateKey.getEncoded(), credential.getPrivateKey().getEncoded());
  }

  @Test
  public void testRemoveCredential() {
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential credential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, 0);

    authenticator.addCredential(credential);

    authenticator.removeCredential(credentialId);
    Assertions.assertEquals(0, authenticator.getCredentials().size());
  }

  @Test
  public void testRemoveAllCredentials() {
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential residentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    authenticator.removeAllCredentials();
    Assertions.assertEquals(0, authenticator.getCredentials().size());
  }

  @Test
  public void testSetUserVerified() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true);

    Assertions.assertTrue((boolean) options.toMap().get("isUserVerified"));
  }
}
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            String virtualAuthenticatorId = ((WebDriver)driver).AddVirtualAuthenticator(options);

            ((WebDriver)driver).RemoveVirtualAuthenticator(virtualAuthenticatorId);
Show full example
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.IdentityModel.Tokens;
using OpenQA.Selenium;
using OpenQA.Selenium.VirtualAuth;
using static OpenQA.Selenium.VirtualAuth.VirtualAuthenticatorOptions;
using System.Collections.Generic;
using System;

namespace SeleniumDocs.VirtualAuthentication
{
    [TestClass]
    public class VirtualAuthenticatorTest : BaseChromeTest
    {
        //A pkcs#8 encoded encrypted RSA private key as a base64 string.
        private static string base64EncodedRSAPK =
                "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"
              + "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"
              + "GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"
              + "9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"
              + "vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"
              + "zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"
              + "XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"
              + "RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"
              + "QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"
              + "S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"
              + "ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"
              + "ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"
              + "OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"
              + "ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"
              + "hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"
              + "WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"
              + "NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"
              + "nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";

        private static byte[] bytes = System.Convert.FromBase64String(base64EncodedRSAPK);
        private string base64EncodedPK = Base64UrlEncoder.Encode(bytes);

        // A pkcs#8 encoded unencrypted EC256 private key as a base64url string.
        private string base64EncodedEC256PK =
              "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"
              + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"
              + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";


        [TestMethod]
        public void VirtualOptionsShouldAllowSettingOptions()
        {
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true)
                .SetHasUserVerification(true)
                .SetIsUserConsenting(true)
                .SetTransport(VirtualAuthenticatorOptions.Transport.USB)
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            Assert.AreEqual(6, options.ToDictionary().Count);
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAuthenticator()
        {
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            // Register a virtual authenticator
            ((WebDriver)driver).AddVirtualAuthenticator(options);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();

            Assert.AreEqual(0, credentialList.Count);
        }


        [TestMethod]
        public void ShouldBeAbleToRemoveAuthenticator()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            String virtualAuthenticatorId = ((WebDriver)driver).AddVirtualAuthenticator(options);

            ((WebDriver)driver).RemoveVirtualAuthenticator(virtualAuthenticatorId);

            // Since the authenticator was removed, any operation using it will throw an error
            Assert.ThrowsException<InvalidOperationException>(() => ((WebDriver)driver).GetCredentials());
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAndAddResidentialKey()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(Protocol.CTAP2)
                .SetHasResidentKey(true)
                .SetHasUserVerification(true)
                .SetIsUserVerified(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);

            ((WebDriver)driver).AddCredential(residentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, credential.Id);
        }

        [TestMethod]
        public void ShouldNotAddResidentCredentialWhenAuthenticatorUsesU2FProtocol()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential credential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, userHandle, 0);

            Assert.ThrowsException<WebDriverArgumentException>(() => ((WebDriver)driver).AddCredential(credential));
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAndAddNonResidentKey()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, nonResidentCredential.Id);
        }

        [TestMethod]
        public void ShouldBeAbleToGetCredential()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(Protocol.CTAP2)
                .SetHasResidentKey(true)
                .SetHasUserVerification(true)
                .SetIsUserVerified(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);

            ((WebDriver)driver).AddCredential(residentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, residentCredential.Id);
            Assert.AreEqual(base64EncodedPK, credential.PrivateKey);
        }

        [TestMethod]
        public void ShouldBeAbleToRemoveCredential()
        {
            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveCredential(credentialId);

            Assert.AreEqual(0, ((WebDriver)driver).GetCredentials().Count);
        }


        [TestMethod]
        public void ShouldBeAbleToRemoveAllCredentias()
        {
            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveAllCredentials();

            Assert.AreEqual(0, ((WebDriver)driver).GetCredentials().Count);
        }

        [TestMethod]
        public void ShouldBeSetVerifiedOption()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true);

            Assert.IsTrue((bool)options.ToDictionary()["isUserVerified"]);
        }
    }
}
    options = VirtualAuthenticatorOptions()

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # Remove virtual authenticator
    driver.remove_virtual_authenticator()
Show full example
import pytest
from base64 import urlsafe_b64decode, urlsafe_b64encode

from selenium.common.exceptions import InvalidArgumentException
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.virtual_authenticator import (
    Credential,
    VirtualAuthenticatorOptions,
)


BASE64__ENCODED_PK = '''
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV
oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ
FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq
GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0
+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM
8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD
/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ
5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe
pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol
L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d
xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi
uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8
K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct
lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa
9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
'''


@pytest.fixture(scope="module", autouse=True)
def driver():
    yield WebDriver()


def test_virtual_authenticator_options():
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True
    options.has_user_verification = True
    options.is_user_consenting = True
    options.transport = VirtualAuthenticatorOptions.Transport.USB
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    assert len(options.to_dict()) == 6


def test_add_authenticator(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # Get list of credentials
    credential_list = driver.get_credentials()

    assert len(credential_list) == 0


def test_remove_authenticator(driver):
    # Create default virtual authenticator option
    options = VirtualAuthenticatorOptions()

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # Remove virtual authenticator
    driver.remove_virtual_authenticator()
    assert driver.virtual_authenticator_id is None


def test_create_and_add_resident_key(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
    options.has_resident_key = True
    options.has_user_verification = True
    options.is_user_verified = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(resident_credential)

    # get list of all the registered credentials 
    credential_list = driver.get_credentials()
    assert len(credential_list) == 1


def test_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a  resident credential using above parameters
    credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)

    # Expect InvalidArgumentException 
    with pytest.raises(InvalidArgumentException):
        driver.add_credential(credential)


def test_create_and_add_non_resident_key(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Non Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a non resident credential using above parameters
    credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(credential)
    
    # get list of all the registered credentials 
    credential_list = driver.get_credentials()
    assert len(credential_list) == 1



def test_get_credential(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
    options.has_resident_key = True
    options.has_user_verfied = True
    options.is_user_verified = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)
    
    # add the credential created to virtual authenticator
    driver.add_credential(credential)

    # get list of all the registered credentials 
    credential_list = driver.get_credentials()

    assert len(credential_list) == 1
    assert credential_list[0].id == urlsafe_b64encode(credential_id).decode()


def test_remove_credential(driver):
    # Create default virtual authenticator options
    options = VirtualAuthenticatorOptions()

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Non Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a non resident credential using above parameters
    credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(credential)

    # remove the credential created from virtual authenticator
    driver.remove_credential(credential.id)

    # credential can also be removed using Byte Array
    # driver.remove_credential(credential_id) 

    assert len(driver.get_credentials()) == 0


def test_remove_all_credentials(driver):
    # Create default virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.has_resident_key = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)
    
    # add the credential created to virtual authenticator
    driver.add_credential(resident_credential)

    # remove all credentials in virtual authenticator
    driver.remove_all_credentials()

    assert len(driver.get_credentials()) == 0


def test_set_user_verified():
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True

    assert options.to_dict().get("isUserVerified") is True
    await driver.addVirtualAuthenticator(options);
    await driver.removeVirtualAuthenticator();
Show full example

const { Builder} = require("selenium-webdriver");
const { Credential, VirtualAuthenticatorOptions, Transport, Protocol } = require("selenium-webdriver/lib/virtual_authenticator");
const assert = require('assert')
const { InvalidArgumentError } = require("selenium-webdriver/lib/error");


describe('Virtual authenticator', function() {
  const BASE64_ENCODED_PK =
    "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr" +
    "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV" +
    "oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ" +
    "FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq" +
    "GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0" +
    "+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM" +
    "8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD" +
    "/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ" +
    "5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe" +
    "pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol" +
    "L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d" +
    "xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi" +
    "uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8" +
    "K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct" +
    "lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa" +
    "9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH" +
    "zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H" +
    "BYGpI8g==";

  const base64EncodedPK =
    "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q" +
    "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU" +
    "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";

  let options;
  let driver;

  before(async function() {
    options = new VirtualAuthenticatorOptions();
    driver = await new Builder().forBrowser('chrome').build();
  });

  after(async() => await driver.quit());

  function arraysEqual(array1, array2) {
    return (array1.length === array2.length &&
      array1.every((item) => array2.includes(item)) &&
      array2.every((item) => array1.includes(item)));
  }

  it('Register a virtual authenticator', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(false);

    // Register a virtual authenticator
    await driver.addVirtualAuthenticator(options);
    let credentialList = await driver.getCredentials();

    assert.equal(0, credentialList.length);
  });

  it('Remove authenticator', async function() {
    await driver.addVirtualAuthenticator(options);
    await driver.removeVirtualAuthenticator();

    // Since the authenticator was removed, any operation using it will throw an error
    try {
      await driver.getCredentials()
    }
    catch (e) {
      if (e instanceof InvalidArgumentError) {
        assert(true)
      }
      else {
        assert(false)
      }
    }
  });

  it('Createa and add residential key', async function() {
    options.setProtocol(Protocol['CTAP2']);
    options.setHasResidentKey(true);
    options.setHasUserVerification(true);
    options.setIsUserVerified(true);

    await driver.addVirtualAuthenticator(options);

    let residentCredential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(residentCredential);
    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
  });

  it('Add resident credential not supported when authenticator uses U2F protocol', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(true);

    await driver.addVirtualAuthenticator(options);

    let credential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(base64EncodedPK, 'base64').toString('binary'),
      0);

    try {
      await driver.addCredential(credential)
    }
    catch (e) {
      if (e instanceof InvalidArgumentError) {
        assert(true)
      }
      else {
        assert(false)
      }
    }
  });

  it('Create and add non residential key', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(false);

    await driver.addVirtualAuthenticator(options);

    let nonResidentCredential = new Credential().createNonResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      Buffer.from(base64EncodedPK, 'base64').toString('binary'),
      0);

    await driver.addCredential(nonResidentCredential);

    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
  });

  it('Get credential', async function() {
    options.setProtocol(Protocol['CTAP2']);
    options.setHasResidentKey(true);
    options.setHasUserVerification(true);
    options.setIsUserVerified(true);

    await driver.addVirtualAuthenticator(options);

    let residentCredential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(residentCredential);

    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
    assert.equal(BASE64_ENCODED_PK, Buffer.from(credentialList[0].privateKey(), 'binary').toString('base64'));
  });

  it('Remove all credentials', async function() {
    await driver.addVirtualAuthenticator(options);

    let nonResidentCredential = new Credential().createNonResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(nonResidentCredential);
    await driver.removeAllCredentials();

    let credentialList = await driver.getCredentials();
    assert.equal(0, credentialList.length);
  });

  it('Set is user verified', async function() {
    options.setIsUserVerified(true);
    assert.equal(options.getIsUserVerified(), true);
  });
});

Create Resident Credential

Cria uma resident (stateful) credential com os requeridos parâmetros.

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);
Show full example
package dev.selenium.interactions;

import dev.selenium.BaseChromeTest;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.InvalidArgumentException;
import org.openqa.selenium.virtualauthenticator.Credential;
import org.openqa.selenium.virtualauthenticator.HasVirtualAuthenticator;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticator;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;

public class VirtualAuthenticatorTest extends BaseChromeTest {

  /**
   * A pkcs#8 encoded encrypted RSA private key as a base64url string.
   */
  private final static String
    base64EncodedRsaPK =
    "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"
    + "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"
    + "GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"
    + "9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"
    + "vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"
    + "zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"
    + "XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"
    + "RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"
    + "QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"
    + "S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"
    + "ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"
    + "ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"
    + "OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"
    + "ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"
    + "hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"
    + "WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"
    + "NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"
    + "nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";

  private final static PKCS8EncodedKeySpec rsaPrivateKey =
    new PKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(base64EncodedRsaPK));

  // A pkcs#8 encoded unencrypted EC256 private key as a base64url string.
  String base64EncodedEC256PK =
    "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"
    + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"
    + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";

  PKCS8EncodedKeySpec ec256PrivateKey =
    new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));

  @Test
  public void testVirtualOptions() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true)
      .setHasUserVerification(true)
      .setIsUserConsenting(true)
      .setTransport(VirtualAuthenticatorOptions.Transport.USB)
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    Assertions.assertEquals(6, options.toMap().size());
  }

  @Test
  public void testCreateAuthenticator() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    List<Credential> credentialList = authenticator.getCredentials();

    Assertions.assertEquals(0, credentialList.size());
  }

  @Test
  public void testRemoveAuthenticator() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions();
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    ((HasVirtualAuthenticator) driver).removeVirtualAuthenticator(authenticator);

    Assertions.assertThrows(InvalidArgumentException.class, authenticator::getCredentials);
  }

  @Test
  public void testCreateAndAddResidentialKey() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasResidentKey(true)
      .setHasUserVerification(true)
      .setIsUserVerified(true);
    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
  }

  @Test
  public void testAddResidentCredentialNotSupportedWhenAuthenticatorUsesU2FProtocol() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(true);

    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    PKCS8EncodedKeySpec privateKey =
      new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential credential = Credential.createResidentCredential(
      credentialId, "localhost", privateKey, userHandle, /*signCount=*/0);

    Assertions.assertThrows(InvalidArgumentException.class,
                            () -> authenticator.addCredential(credential));
  }


  @Test
  public void testCreateAndAddNonResidentialKey() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    Credential nonResidentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", ec256PrivateKey, /*signCount=*/0);
    authenticator.addCredential(nonResidentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
  }

  @Test
  public void testGetCredential() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasResidentKey(true)
      .setHasUserVerification(true)
      .setIsUserVerified(true);
    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
    Assertions.assertArrayEquals(rsaPrivateKey.getEncoded(), credential.getPrivateKey().getEncoded());
  }

  @Test
  public void testRemoveCredential() {
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential credential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, 0);

    authenticator.addCredential(credential);

    authenticator.removeCredential(credentialId);
    Assertions.assertEquals(0, authenticator.getCredentials().size());
  }

  @Test
  public void testRemoveAllCredentials() {
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential residentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    authenticator.removeAllCredentials();
    Assertions.assertEquals(0, authenticator.getCredentials().size());
  }

  @Test
  public void testSetUserVerified() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true);

    Assertions.assertTrue((boolean) options.toMap().get("isUserVerified"));
  }
}
            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);
Show full example
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.IdentityModel.Tokens;
using OpenQA.Selenium;
using OpenQA.Selenium.VirtualAuth;
using static OpenQA.Selenium.VirtualAuth.VirtualAuthenticatorOptions;
using System.Collections.Generic;
using System;

namespace SeleniumDocs.VirtualAuthentication
{
    [TestClass]
    public class VirtualAuthenticatorTest : BaseChromeTest
    {
        //A pkcs#8 encoded encrypted RSA private key as a base64 string.
        private static string base64EncodedRSAPK =
                "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"
              + "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"
              + "GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"
              + "9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"
              + "vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"
              + "zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"
              + "XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"
              + "RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"
              + "QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"
              + "S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"
              + "ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"
              + "ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"
              + "OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"
              + "ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"
              + "hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"
              + "WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"
              + "NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"
              + "nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";

        private static byte[] bytes = System.Convert.FromBase64String(base64EncodedRSAPK);
        private string base64EncodedPK = Base64UrlEncoder.Encode(bytes);

        // A pkcs#8 encoded unencrypted EC256 private key as a base64url string.
        private string base64EncodedEC256PK =
              "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"
              + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"
              + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";


        [TestMethod]
        public void VirtualOptionsShouldAllowSettingOptions()
        {
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true)
                .SetHasUserVerification(true)
                .SetIsUserConsenting(true)
                .SetTransport(VirtualAuthenticatorOptions.Transport.USB)
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            Assert.AreEqual(6, options.ToDictionary().Count);
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAuthenticator()
        {
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            // Register a virtual authenticator
            ((WebDriver)driver).AddVirtualAuthenticator(options);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();

            Assert.AreEqual(0, credentialList.Count);
        }


        [TestMethod]
        public void ShouldBeAbleToRemoveAuthenticator()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            String virtualAuthenticatorId = ((WebDriver)driver).AddVirtualAuthenticator(options);

            ((WebDriver)driver).RemoveVirtualAuthenticator(virtualAuthenticatorId);

            // Since the authenticator was removed, any operation using it will throw an error
            Assert.ThrowsException<InvalidOperationException>(() => ((WebDriver)driver).GetCredentials());
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAndAddResidentialKey()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(Protocol.CTAP2)
                .SetHasResidentKey(true)
                .SetHasUserVerification(true)
                .SetIsUserVerified(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);

            ((WebDriver)driver).AddCredential(residentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, credential.Id);
        }

        [TestMethod]
        public void ShouldNotAddResidentCredentialWhenAuthenticatorUsesU2FProtocol()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential credential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, userHandle, 0);

            Assert.ThrowsException<WebDriverArgumentException>(() => ((WebDriver)driver).AddCredential(credential));
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAndAddNonResidentKey()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, nonResidentCredential.Id);
        }

        [TestMethod]
        public void ShouldBeAbleToGetCredential()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(Protocol.CTAP2)
                .SetHasResidentKey(true)
                .SetHasUserVerification(true)
                .SetIsUserVerified(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);

            ((WebDriver)driver).AddCredential(residentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, residentCredential.Id);
            Assert.AreEqual(base64EncodedPK, credential.PrivateKey);
        }

        [TestMethod]
        public void ShouldBeAbleToRemoveCredential()
        {
            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveCredential(credentialId);

            Assert.AreEqual(0, ((WebDriver)driver).GetCredentials().Count);
        }


        [TestMethod]
        public void ShouldBeAbleToRemoveAllCredentias()
        {
            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveAllCredentials();

            Assert.AreEqual(0, ((WebDriver)driver).GetCredentials().Count);
        }

        [TestMethod]
        public void ShouldBeSetVerifiedOption()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true);

            Assert.IsTrue((bool)options.ToDictionary()["isUserVerified"]);
        }
    }
}
    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)
Show full example
import pytest
from base64 import urlsafe_b64decode, urlsafe_b64encode

from selenium.common.exceptions import InvalidArgumentException
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.virtual_authenticator import (
    Credential,
    VirtualAuthenticatorOptions,
)


BASE64__ENCODED_PK = '''
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV
oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ
FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq
GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0
+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM
8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD
/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ
5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe
pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol
L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d
xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi
uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8
K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct
lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa
9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
'''


@pytest.fixture(scope="module", autouse=True)
def driver():
    yield WebDriver()


def test_virtual_authenticator_options():
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True
    options.has_user_verification = True
    options.is_user_consenting = True
    options.transport = VirtualAuthenticatorOptions.Transport.USB
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    assert len(options.to_dict()) == 6


def test_add_authenticator(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # Get list of credentials
    credential_list = driver.get_credentials()

    assert len(credential_list) == 0


def test_remove_authenticator(driver):
    # Create default virtual authenticator option
    options = VirtualAuthenticatorOptions()

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # Remove virtual authenticator
    driver.remove_virtual_authenticator()
    assert driver.virtual_authenticator_id is None


def test_create_and_add_resident_key(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
    options.has_resident_key = True
    options.has_user_verification = True
    options.is_user_verified = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(resident_credential)

    # get list of all the registered credentials 
    credential_list = driver.get_credentials()
    assert len(credential_list) == 1


def test_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a  resident credential using above parameters
    credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)

    # Expect InvalidArgumentException 
    with pytest.raises(InvalidArgumentException):
        driver.add_credential(credential)


def test_create_and_add_non_resident_key(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Non Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a non resident credential using above parameters
    credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(credential)
    
    # get list of all the registered credentials 
    credential_list = driver.get_credentials()
    assert len(credential_list) == 1



def test_get_credential(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
    options.has_resident_key = True
    options.has_user_verfied = True
    options.is_user_verified = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)
    
    # add the credential created to virtual authenticator
    driver.add_credential(credential)

    # get list of all the registered credentials 
    credential_list = driver.get_credentials()

    assert len(credential_list) == 1
    assert credential_list[0].id == urlsafe_b64encode(credential_id).decode()


def test_remove_credential(driver):
    # Create default virtual authenticator options
    options = VirtualAuthenticatorOptions()

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Non Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a non resident credential using above parameters
    credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(credential)

    # remove the credential created from virtual authenticator
    driver.remove_credential(credential.id)

    # credential can also be removed using Byte Array
    # driver.remove_credential(credential_id) 

    assert len(driver.get_credentials()) == 0


def test_remove_all_credentials(driver):
    # Create default virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.has_resident_key = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)
    
    # add the credential created to virtual authenticator
    driver.add_credential(resident_credential)

    # remove all credentials in virtual authenticator
    driver.remove_all_credentials()

    assert len(driver.get_credentials()) == 0


def test_set_user_verified():
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True

    assert options.to_dict().get("isUserVerified") is True
    options.setProtocol(Protocol['CTAP2']);
    options.setHasResidentKey(true);
    options.setHasUserVerification(true);
    options.setIsUserVerified(true);

    await driver.addVirtualAuthenticator(options);

    let residentCredential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(residentCredential);
Show full example

const { Builder} = require("selenium-webdriver");
const { Credential, VirtualAuthenticatorOptions, Transport, Protocol } = require("selenium-webdriver/lib/virtual_authenticator");
const assert = require('assert')
const { InvalidArgumentError } = require("selenium-webdriver/lib/error");


describe('Virtual authenticator', function() {
  const BASE64_ENCODED_PK =
    "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr" +
    "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV" +
    "oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ" +
    "FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq" +
    "GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0" +
    "+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM" +
    "8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD" +
    "/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ" +
    "5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe" +
    "pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol" +
    "L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d" +
    "xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi" +
    "uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8" +
    "K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct" +
    "lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa" +
    "9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH" +
    "zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H" +
    "BYGpI8g==";

  const base64EncodedPK =
    "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q" +
    "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU" +
    "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";

  let options;
  let driver;

  before(async function() {
    options = new VirtualAuthenticatorOptions();
    driver = await new Builder().forBrowser('chrome').build();
  });

  after(async() => await driver.quit());

  function arraysEqual(array1, array2) {
    return (array1.length === array2.length &&
      array1.every((item) => array2.includes(item)) &&
      array2.every((item) => array1.includes(item)));
  }

  it('Register a virtual authenticator', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(false);

    // Register a virtual authenticator
    await driver.addVirtualAuthenticator(options);
    let credentialList = await driver.getCredentials();

    assert.equal(0, credentialList.length);
  });

  it('Remove authenticator', async function() {
    await driver.addVirtualAuthenticator(options);
    await driver.removeVirtualAuthenticator();

    // Since the authenticator was removed, any operation using it will throw an error
    try {
      await driver.getCredentials()
    }
    catch (e) {
      if (e instanceof InvalidArgumentError) {
        assert(true)
      }
      else {
        assert(false)
      }
    }
  });

  it('Createa and add residential key', async function() {
    options.setProtocol(Protocol['CTAP2']);
    options.setHasResidentKey(true);
    options.setHasUserVerification(true);
    options.setIsUserVerified(true);

    await driver.addVirtualAuthenticator(options);

    let residentCredential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(residentCredential);
    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
  });

  it('Add resident credential not supported when authenticator uses U2F protocol', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(true);

    await driver.addVirtualAuthenticator(options);

    let credential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(base64EncodedPK, 'base64').toString('binary'),
      0);

    try {
      await driver.addCredential(credential)
    }
    catch (e) {
      if (e instanceof InvalidArgumentError) {
        assert(true)
      }
      else {
        assert(false)
      }
    }
  });

  it('Create and add non residential key', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(false);

    await driver.addVirtualAuthenticator(options);

    let nonResidentCredential = new Credential().createNonResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      Buffer.from(base64EncodedPK, 'base64').toString('binary'),
      0);

    await driver.addCredential(nonResidentCredential);

    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
  });

  it('Get credential', async function() {
    options.setProtocol(Protocol['CTAP2']);
    options.setHasResidentKey(true);
    options.setHasUserVerification(true);
    options.setIsUserVerified(true);

    await driver.addVirtualAuthenticator(options);

    let residentCredential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(residentCredential);

    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
    assert.equal(BASE64_ENCODED_PK, Buffer.from(credentialList[0].privateKey(), 'binary').toString('base64'));
  });

  it('Remove all credentials', async function() {
    await driver.addVirtualAuthenticator(options);

    let nonResidentCredential = new Credential().createNonResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(nonResidentCredential);
    await driver.removeAllCredentials();

    let credentialList = await driver.getCredentials();
    assert.equal(0, credentialList.length);
  });

  it('Set is user verified', async function() {
    options.setIsUserVerified(true);
    assert.equal(options.getIsUserVerified(), true);
  });
});

Create Non-Resident Credential

Cria uma resident (stateless) credential com os requeridos parâmetros.

    byte[] credentialId = {1, 2, 3, 4};
    Credential nonResidentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", ec256PrivateKey, /*signCount=*/0);
Show full example
package dev.selenium.interactions;

import dev.selenium.BaseChromeTest;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.InvalidArgumentException;
import org.openqa.selenium.virtualauthenticator.Credential;
import org.openqa.selenium.virtualauthenticator.HasVirtualAuthenticator;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticator;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;

public class VirtualAuthenticatorTest extends BaseChromeTest {

  /**
   * A pkcs#8 encoded encrypted RSA private key as a base64url string.
   */
  private final static String
    base64EncodedRsaPK =
    "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"
    + "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"
    + "GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"
    + "9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"
    + "vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"
    + "zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"
    + "XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"
    + "RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"
    + "QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"
    + "S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"
    + "ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"
    + "ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"
    + "OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"
    + "ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"
    + "hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"
    + "WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"
    + "NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"
    + "nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";

  private final static PKCS8EncodedKeySpec rsaPrivateKey =
    new PKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(base64EncodedRsaPK));

  // A pkcs#8 encoded unencrypted EC256 private key as a base64url string.
  String base64EncodedEC256PK =
    "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"
    + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"
    + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";

  PKCS8EncodedKeySpec ec256PrivateKey =
    new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));

  @Test
  public void testVirtualOptions() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true)
      .setHasUserVerification(true)
      .setIsUserConsenting(true)
      .setTransport(VirtualAuthenticatorOptions.Transport.USB)
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    Assertions.assertEquals(6, options.toMap().size());
  }

  @Test
  public void testCreateAuthenticator() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    List<Credential> credentialList = authenticator.getCredentials();

    Assertions.assertEquals(0, credentialList.size());
  }

  @Test
  public void testRemoveAuthenticator() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions();
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    ((HasVirtualAuthenticator) driver).removeVirtualAuthenticator(authenticator);

    Assertions.assertThrows(InvalidArgumentException.class, authenticator::getCredentials);
  }

  @Test
  public void testCreateAndAddResidentialKey() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasResidentKey(true)
      .setHasUserVerification(true)
      .setIsUserVerified(true);
    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
  }

  @Test
  public void testAddResidentCredentialNotSupportedWhenAuthenticatorUsesU2FProtocol() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(true);

    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    PKCS8EncodedKeySpec privateKey =
      new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential credential = Credential.createResidentCredential(
      credentialId, "localhost", privateKey, userHandle, /*signCount=*/0);

    Assertions.assertThrows(InvalidArgumentException.class,
                            () -> authenticator.addCredential(credential));
  }


  @Test
  public void testCreateAndAddNonResidentialKey() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    Credential nonResidentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", ec256PrivateKey, /*signCount=*/0);
    authenticator.addCredential(nonResidentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
  }

  @Test
  public void testGetCredential() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasResidentKey(true)
      .setHasUserVerification(true)
      .setIsUserVerified(true);
    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
    Assertions.assertArrayEquals(rsaPrivateKey.getEncoded(), credential.getPrivateKey().getEncoded());
  }

  @Test
  public void testRemoveCredential() {
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential credential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, 0);

    authenticator.addCredential(credential);

    authenticator.removeCredential(credentialId);
    Assertions.assertEquals(0, authenticator.getCredentials().size());
  }

  @Test
  public void testRemoveAllCredentials() {
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential residentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    authenticator.removeAllCredentials();
    Assertions.assertEquals(0, authenticator.getCredentials().size());
  }

  @Test
  public void testSetUserVerified() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true);

    Assertions.assertTrue((boolean) options.toMap().get("isUserVerified"));
  }
}
            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);
Show full example
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.IdentityModel.Tokens;
using OpenQA.Selenium;
using OpenQA.Selenium.VirtualAuth;
using static OpenQA.Selenium.VirtualAuth.VirtualAuthenticatorOptions;
using System.Collections.Generic;
using System;

namespace SeleniumDocs.VirtualAuthentication
{
    [TestClass]
    public class VirtualAuthenticatorTest : BaseChromeTest
    {
        //A pkcs#8 encoded encrypted RSA private key as a base64 string.
        private static string base64EncodedRSAPK =
                "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"
              + "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"
              + "GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"
              + "9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"
              + "vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"
              + "zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"
              + "XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"
              + "RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"
              + "QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"
              + "S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"
              + "ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"
              + "ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"
              + "OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"
              + "ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"
              + "hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"
              + "WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"
              + "NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"
              + "nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";

        private static byte[] bytes = System.Convert.FromBase64String(base64EncodedRSAPK);
        private string base64EncodedPK = Base64UrlEncoder.Encode(bytes);

        // A pkcs#8 encoded unencrypted EC256 private key as a base64url string.
        private string base64EncodedEC256PK =
              "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"
              + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"
              + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";


        [TestMethod]
        public void VirtualOptionsShouldAllowSettingOptions()
        {
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true)
                .SetHasUserVerification(true)
                .SetIsUserConsenting(true)
                .SetTransport(VirtualAuthenticatorOptions.Transport.USB)
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            Assert.AreEqual(6, options.ToDictionary().Count);
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAuthenticator()
        {
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            // Register a virtual authenticator
            ((WebDriver)driver).AddVirtualAuthenticator(options);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();

            Assert.AreEqual(0, credentialList.Count);
        }


        [TestMethod]
        public void ShouldBeAbleToRemoveAuthenticator()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            String virtualAuthenticatorId = ((WebDriver)driver).AddVirtualAuthenticator(options);

            ((WebDriver)driver).RemoveVirtualAuthenticator(virtualAuthenticatorId);

            // Since the authenticator was removed, any operation using it will throw an error
            Assert.ThrowsException<InvalidOperationException>(() => ((WebDriver)driver).GetCredentials());
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAndAddResidentialKey()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(Protocol.CTAP2)
                .SetHasResidentKey(true)
                .SetHasUserVerification(true)
                .SetIsUserVerified(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);

            ((WebDriver)driver).AddCredential(residentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, credential.Id);
        }

        [TestMethod]
        public void ShouldNotAddResidentCredentialWhenAuthenticatorUsesU2FProtocol()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential credential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, userHandle, 0);

            Assert.ThrowsException<WebDriverArgumentException>(() => ((WebDriver)driver).AddCredential(credential));
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAndAddNonResidentKey()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, nonResidentCredential.Id);
        }

        [TestMethod]
        public void ShouldBeAbleToGetCredential()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(Protocol.CTAP2)
                .SetHasResidentKey(true)
                .SetHasUserVerification(true)
                .SetIsUserVerified(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);

            ((WebDriver)driver).AddCredential(residentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, residentCredential.Id);
            Assert.AreEqual(base64EncodedPK, credential.PrivateKey);
        }

        [TestMethod]
        public void ShouldBeAbleToRemoveCredential()
        {
            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveCredential(credentialId);

            Assert.AreEqual(0, ((WebDriver)driver).GetCredentials().Count);
        }


        [TestMethod]
        public void ShouldBeAbleToRemoveAllCredentias()
        {
            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveAllCredentials();

            Assert.AreEqual(0, ((WebDriver)driver).GetCredentials().Count);
        }

        [TestMethod]
        public void ShouldBeSetVerifiedOption()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true);

            Assert.IsTrue((bool)options.ToDictionary()["isUserVerified"]);
        }
    }
}
    # parameters for Non Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a non resident credential using above parameters
    credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)
Show full example
import pytest
from base64 import urlsafe_b64decode, urlsafe_b64encode

from selenium.common.exceptions import InvalidArgumentException
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.virtual_authenticator import (
    Credential,
    VirtualAuthenticatorOptions,
)


BASE64__ENCODED_PK = '''
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV
oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ
FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq
GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0
+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM
8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD
/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ
5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe
pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol
L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d
xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi
uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8
K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct
lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa
9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
'''


@pytest.fixture(scope="module", autouse=True)
def driver():
    yield WebDriver()


def test_virtual_authenticator_options():
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True
    options.has_user_verification = True
    options.is_user_consenting = True
    options.transport = VirtualAuthenticatorOptions.Transport.USB
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    assert len(options.to_dict()) == 6


def test_add_authenticator(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # Get list of credentials
    credential_list = driver.get_credentials()

    assert len(credential_list) == 0


def test_remove_authenticator(driver):
    # Create default virtual authenticator option
    options = VirtualAuthenticatorOptions()

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # Remove virtual authenticator
    driver.remove_virtual_authenticator()
    assert driver.virtual_authenticator_id is None


def test_create_and_add_resident_key(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
    options.has_resident_key = True
    options.has_user_verification = True
    options.is_user_verified = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(resident_credential)

    # get list of all the registered credentials 
    credential_list = driver.get_credentials()
    assert len(credential_list) == 1


def test_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a  resident credential using above parameters
    credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)

    # Expect InvalidArgumentException 
    with pytest.raises(InvalidArgumentException):
        driver.add_credential(credential)


def test_create_and_add_non_resident_key(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Non Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a non resident credential using above parameters
    credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(credential)
    
    # get list of all the registered credentials 
    credential_list = driver.get_credentials()
    assert len(credential_list) == 1



def test_get_credential(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
    options.has_resident_key = True
    options.has_user_verfied = True
    options.is_user_verified = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)
    
    # add the credential created to virtual authenticator
    driver.add_credential(credential)

    # get list of all the registered credentials 
    credential_list = driver.get_credentials()

    assert len(credential_list) == 1
    assert credential_list[0].id == urlsafe_b64encode(credential_id).decode()


def test_remove_credential(driver):
    # Create default virtual authenticator options
    options = VirtualAuthenticatorOptions()

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Non Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a non resident credential using above parameters
    credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(credential)

    # remove the credential created from virtual authenticator
    driver.remove_credential(credential.id)

    # credential can also be removed using Byte Array
    # driver.remove_credential(credential_id) 

    assert len(driver.get_credentials()) == 0


def test_remove_all_credentials(driver):
    # Create default virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.has_resident_key = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)
    
    # add the credential created to virtual authenticator
    driver.add_credential(resident_credential)

    # remove all credentials in virtual authenticator
    driver.remove_all_credentials()

    assert len(driver.get_credentials()) == 0


def test_set_user_verified():
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True

    assert options.to_dict().get("isUserVerified") is True
    let nonResidentCredential = new Credential().createNonResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      Buffer.from(base64EncodedPK, 'base64').toString('binary'),
      0);
Show full example

const { Builder} = require("selenium-webdriver");
const { Credential, VirtualAuthenticatorOptions, Transport, Protocol } = require("selenium-webdriver/lib/virtual_authenticator");
const assert = require('assert')
const { InvalidArgumentError } = require("selenium-webdriver/lib/error");


describe('Virtual authenticator', function() {
  const BASE64_ENCODED_PK =
    "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr" +
    "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV" +
    "oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ" +
    "FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq" +
    "GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0" +
    "+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM" +
    "8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD" +
    "/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ" +
    "5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe" +
    "pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol" +
    "L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d" +
    "xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi" +
    "uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8" +
    "K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct" +
    "lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa" +
    "9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH" +
    "zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H" +
    "BYGpI8g==";

  const base64EncodedPK =
    "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q" +
    "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU" +
    "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";

  let options;
  let driver;

  before(async function() {
    options = new VirtualAuthenticatorOptions();
    driver = await new Builder().forBrowser('chrome').build();
  });

  after(async() => await driver.quit());

  function arraysEqual(array1, array2) {
    return (array1.length === array2.length &&
      array1.every((item) => array2.includes(item)) &&
      array2.every((item) => array1.includes(item)));
  }

  it('Register a virtual authenticator', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(false);

    // Register a virtual authenticator
    await driver.addVirtualAuthenticator(options);
    let credentialList = await driver.getCredentials();

    assert.equal(0, credentialList.length);
  });

  it('Remove authenticator', async function() {
    await driver.addVirtualAuthenticator(options);
    await driver.removeVirtualAuthenticator();

    // Since the authenticator was removed, any operation using it will throw an error
    try {
      await driver.getCredentials()
    }
    catch (e) {
      if (e instanceof InvalidArgumentError) {
        assert(true)
      }
      else {
        assert(false)
      }
    }
  });

  it('Createa and add residential key', async function() {
    options.setProtocol(Protocol['CTAP2']);
    options.setHasResidentKey(true);
    options.setHasUserVerification(true);
    options.setIsUserVerified(true);

    await driver.addVirtualAuthenticator(options);

    let residentCredential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(residentCredential);
    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
  });

  it('Add resident credential not supported when authenticator uses U2F protocol', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(true);

    await driver.addVirtualAuthenticator(options);

    let credential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(base64EncodedPK, 'base64').toString('binary'),
      0);

    try {
      await driver.addCredential(credential)
    }
    catch (e) {
      if (e instanceof InvalidArgumentError) {
        assert(true)
      }
      else {
        assert(false)
      }
    }
  });

  it('Create and add non residential key', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(false);

    await driver.addVirtualAuthenticator(options);

    let nonResidentCredential = new Credential().createNonResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      Buffer.from(base64EncodedPK, 'base64').toString('binary'),
      0);

    await driver.addCredential(nonResidentCredential);

    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
  });

  it('Get credential', async function() {
    options.setProtocol(Protocol['CTAP2']);
    options.setHasResidentKey(true);
    options.setHasUserVerification(true);
    options.setIsUserVerified(true);

    await driver.addVirtualAuthenticator(options);

    let residentCredential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(residentCredential);

    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
    assert.equal(BASE64_ENCODED_PK, Buffer.from(credentialList[0].privateKey(), 'binary').toString('base64'));
  });

  it('Remove all credentials', async function() {
    await driver.addVirtualAuthenticator(options);

    let nonResidentCredential = new Credential().createNonResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(nonResidentCredential);
    await driver.removeAllCredentials();

    let credentialList = await driver.getCredentials();
    assert.equal(0, credentialList.length);
  });

  it('Set is user verified', async function() {
    options.setIsUserVerified(true);
    assert.equal(options.getIsUserVerified(), true);
  });
});

Add Credential

Registra a credencial com o autenticador.

    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    Credential nonResidentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", ec256PrivateKey, /*signCount=*/0);
    authenticator.addCredential(nonResidentCredential);
Show full example
package dev.selenium.interactions;

import dev.selenium.BaseChromeTest;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.InvalidArgumentException;
import org.openqa.selenium.virtualauthenticator.Credential;
import org.openqa.selenium.virtualauthenticator.HasVirtualAuthenticator;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticator;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;

public class VirtualAuthenticatorTest extends BaseChromeTest {

  /**
   * A pkcs#8 encoded encrypted RSA private key as a base64url string.
   */
  private final static String
    base64EncodedRsaPK =
    "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"
    + "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"
    + "GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"
    + "9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"
    + "vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"
    + "zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"
    + "XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"
    + "RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"
    + "QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"
    + "S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"
    + "ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"
    + "ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"
    + "OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"
    + "ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"
    + "hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"
    + "WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"
    + "NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"
    + "nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";

  private final static PKCS8EncodedKeySpec rsaPrivateKey =
    new PKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(base64EncodedRsaPK));

  // A pkcs#8 encoded unencrypted EC256 private key as a base64url string.
  String base64EncodedEC256PK =
    "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"
    + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"
    + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";

  PKCS8EncodedKeySpec ec256PrivateKey =
    new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));

  @Test
  public void testVirtualOptions() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true)
      .setHasUserVerification(true)
      .setIsUserConsenting(true)
      .setTransport(VirtualAuthenticatorOptions.Transport.USB)
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    Assertions.assertEquals(6, options.toMap().size());
  }

  @Test
  public void testCreateAuthenticator() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    List<Credential> credentialList = authenticator.getCredentials();

    Assertions.assertEquals(0, credentialList.size());
  }

  @Test
  public void testRemoveAuthenticator() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions();
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    ((HasVirtualAuthenticator) driver).removeVirtualAuthenticator(authenticator);

    Assertions.assertThrows(InvalidArgumentException.class, authenticator::getCredentials);
  }

  @Test
  public void testCreateAndAddResidentialKey() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasResidentKey(true)
      .setHasUserVerification(true)
      .setIsUserVerified(true);
    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
  }

  @Test
  public void testAddResidentCredentialNotSupportedWhenAuthenticatorUsesU2FProtocol() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(true);

    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    PKCS8EncodedKeySpec privateKey =
      new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential credential = Credential.createResidentCredential(
      credentialId, "localhost", privateKey, userHandle, /*signCount=*/0);

    Assertions.assertThrows(InvalidArgumentException.class,
                            () -> authenticator.addCredential(credential));
  }


  @Test
  public void testCreateAndAddNonResidentialKey() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    Credential nonResidentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", ec256PrivateKey, /*signCount=*/0);
    authenticator.addCredential(nonResidentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
  }

  @Test
  public void testGetCredential() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasResidentKey(true)
      .setHasUserVerification(true)
      .setIsUserVerified(true);
    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
    Assertions.assertArrayEquals(rsaPrivateKey.getEncoded(), credential.getPrivateKey().getEncoded());
  }

  @Test
  public void testRemoveCredential() {
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential credential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, 0);

    authenticator.addCredential(credential);

    authenticator.removeCredential(credentialId);
    Assertions.assertEquals(0, authenticator.getCredentials().size());
  }

  @Test
  public void testRemoveAllCredentials() {
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential residentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    authenticator.removeAllCredentials();
    Assertions.assertEquals(0, authenticator.getCredentials().size());
  }

  @Test
  public void testSetUserVerified() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true);

    Assertions.assertTrue((boolean) options.toMap().get("isUserVerified"));
  }
}
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);
Show full example
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.IdentityModel.Tokens;
using OpenQA.Selenium;
using OpenQA.Selenium.VirtualAuth;
using static OpenQA.Selenium.VirtualAuth.VirtualAuthenticatorOptions;
using System.Collections.Generic;
using System;

namespace SeleniumDocs.VirtualAuthentication
{
    [TestClass]
    public class VirtualAuthenticatorTest : BaseChromeTest
    {
        //A pkcs#8 encoded encrypted RSA private key as a base64 string.
        private static string base64EncodedRSAPK =
                "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"
              + "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"
              + "GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"
              + "9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"
              + "vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"
              + "zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"
              + "XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"
              + "RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"
              + "QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"
              + "S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"
              + "ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"
              + "ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"
              + "OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"
              + "ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"
              + "hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"
              + "WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"
              + "NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"
              + "nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";

        private static byte[] bytes = System.Convert.FromBase64String(base64EncodedRSAPK);
        private string base64EncodedPK = Base64UrlEncoder.Encode(bytes);

        // A pkcs#8 encoded unencrypted EC256 private key as a base64url string.
        private string base64EncodedEC256PK =
              "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"
              + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"
              + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";


        [TestMethod]
        public void VirtualOptionsShouldAllowSettingOptions()
        {
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true)
                .SetHasUserVerification(true)
                .SetIsUserConsenting(true)
                .SetTransport(VirtualAuthenticatorOptions.Transport.USB)
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            Assert.AreEqual(6, options.ToDictionary().Count);
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAuthenticator()
        {
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            // Register a virtual authenticator
            ((WebDriver)driver).AddVirtualAuthenticator(options);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();

            Assert.AreEqual(0, credentialList.Count);
        }


        [TestMethod]
        public void ShouldBeAbleToRemoveAuthenticator()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            String virtualAuthenticatorId = ((WebDriver)driver).AddVirtualAuthenticator(options);

            ((WebDriver)driver).RemoveVirtualAuthenticator(virtualAuthenticatorId);

            // Since the authenticator was removed, any operation using it will throw an error
            Assert.ThrowsException<InvalidOperationException>(() => ((WebDriver)driver).GetCredentials());
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAndAddResidentialKey()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(Protocol.CTAP2)
                .SetHasResidentKey(true)
                .SetHasUserVerification(true)
                .SetIsUserVerified(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);

            ((WebDriver)driver).AddCredential(residentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, credential.Id);
        }

        [TestMethod]
        public void ShouldNotAddResidentCredentialWhenAuthenticatorUsesU2FProtocol()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential credential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, userHandle, 0);

            Assert.ThrowsException<WebDriverArgumentException>(() => ((WebDriver)driver).AddCredential(credential));
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAndAddNonResidentKey()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, nonResidentCredential.Id);
        }

        [TestMethod]
        public void ShouldBeAbleToGetCredential()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(Protocol.CTAP2)
                .SetHasResidentKey(true)
                .SetHasUserVerification(true)
                .SetIsUserVerified(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);

            ((WebDriver)driver).AddCredential(residentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, residentCredential.Id);
            Assert.AreEqual(base64EncodedPK, credential.PrivateKey);
        }

        [TestMethod]
        public void ShouldBeAbleToRemoveCredential()
        {
            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveCredential(credentialId);

            Assert.AreEqual(0, ((WebDriver)driver).GetCredentials().Count);
        }


        [TestMethod]
        public void ShouldBeAbleToRemoveAllCredentias()
        {
            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveAllCredentials();

            Assert.AreEqual(0, ((WebDriver)driver).GetCredentials().Count);
        }

        [TestMethod]
        public void ShouldBeSetVerifiedOption()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true);

            Assert.IsTrue((bool)options.ToDictionary()["isUserVerified"]);
        }
    }
}
    driver.add_credential(credential)
Show full example
import pytest
from base64 import urlsafe_b64decode, urlsafe_b64encode

from selenium.common.exceptions import InvalidArgumentException
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.virtual_authenticator import (
    Credential,
    VirtualAuthenticatorOptions,
)


BASE64__ENCODED_PK = '''
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV
oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ
FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq
GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0
+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM
8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD
/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ
5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe
pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol
L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d
xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi
uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8
K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct
lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa
9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
'''


@pytest.fixture(scope="module", autouse=True)
def driver():
    yield WebDriver()


def test_virtual_authenticator_options():
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True
    options.has_user_verification = True
    options.is_user_consenting = True
    options.transport = VirtualAuthenticatorOptions.Transport.USB
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    assert len(options.to_dict()) == 6


def test_add_authenticator(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # Get list of credentials
    credential_list = driver.get_credentials()

    assert len(credential_list) == 0


def test_remove_authenticator(driver):
    # Create default virtual authenticator option
    options = VirtualAuthenticatorOptions()

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # Remove virtual authenticator
    driver.remove_virtual_authenticator()
    assert driver.virtual_authenticator_id is None


def test_create_and_add_resident_key(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
    options.has_resident_key = True
    options.has_user_verification = True
    options.is_user_verified = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(resident_credential)

    # get list of all the registered credentials 
    credential_list = driver.get_credentials()
    assert len(credential_list) == 1


def test_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a  resident credential using above parameters
    credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)

    # Expect InvalidArgumentException 
    with pytest.raises(InvalidArgumentException):
        driver.add_credential(credential)


def test_create_and_add_non_resident_key(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Non Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a non resident credential using above parameters
    credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(credential)
    
    # get list of all the registered credentials 
    credential_list = driver.get_credentials()
    assert len(credential_list) == 1



def test_get_credential(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
    options.has_resident_key = True
    options.has_user_verfied = True
    options.is_user_verified = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)
    
    # add the credential created to virtual authenticator
    driver.add_credential(credential)

    # get list of all the registered credentials 
    credential_list = driver.get_credentials()

    assert len(credential_list) == 1
    assert credential_list[0].id == urlsafe_b64encode(credential_id).decode()


def test_remove_credential(driver):
    # Create default virtual authenticator options
    options = VirtualAuthenticatorOptions()

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Non Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a non resident credential using above parameters
    credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(credential)

    # remove the credential created from virtual authenticator
    driver.remove_credential(credential.id)

    # credential can also be removed using Byte Array
    # driver.remove_credential(credential_id) 

    assert len(driver.get_credentials()) == 0


def test_remove_all_credentials(driver):
    # Create default virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.has_resident_key = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)
    
    # add the credential created to virtual authenticator
    driver.add_credential(resident_credential)

    # remove all credentials in virtual authenticator
    driver.remove_all_credentials()

    assert len(driver.get_credentials()) == 0


def test_set_user_verified():
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True

    assert options.to_dict().get("isUserVerified") is True
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(false);

    await driver.addVirtualAuthenticator(options);

    let nonResidentCredential = new Credential().createNonResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      Buffer.from(base64EncodedPK, 'base64').toString('binary'),
      0);

    await driver.addCredential(nonResidentCredential);
Show full example

const { Builder} = require("selenium-webdriver");
const { Credential, VirtualAuthenticatorOptions, Transport, Protocol } = require("selenium-webdriver/lib/virtual_authenticator");
const assert = require('assert')
const { InvalidArgumentError } = require("selenium-webdriver/lib/error");


describe('Virtual authenticator', function() {
  const BASE64_ENCODED_PK =
    "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr" +
    "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV" +
    "oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ" +
    "FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq" +
    "GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0" +
    "+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM" +
    "8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD" +
    "/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ" +
    "5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe" +
    "pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol" +
    "L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d" +
    "xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi" +
    "uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8" +
    "K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct" +
    "lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa" +
    "9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH" +
    "zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H" +
    "BYGpI8g==";

  const base64EncodedPK =
    "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q" +
    "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU" +
    "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";

  let options;
  let driver;

  before(async function() {
    options = new VirtualAuthenticatorOptions();
    driver = await new Builder().forBrowser('chrome').build();
  });

  after(async() => await driver.quit());

  function arraysEqual(array1, array2) {
    return (array1.length === array2.length &&
      array1.every((item) => array2.includes(item)) &&
      array2.every((item) => array1.includes(item)));
  }

  it('Register a virtual authenticator', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(false);

    // Register a virtual authenticator
    await driver.addVirtualAuthenticator(options);
    let credentialList = await driver.getCredentials();

    assert.equal(0, credentialList.length);
  });

  it('Remove authenticator', async function() {
    await driver.addVirtualAuthenticator(options);
    await driver.removeVirtualAuthenticator();

    // Since the authenticator was removed, any operation using it will throw an error
    try {
      await driver.getCredentials()
    }
    catch (e) {
      if (e instanceof InvalidArgumentError) {
        assert(true)
      }
      else {
        assert(false)
      }
    }
  });

  it('Createa and add residential key', async function() {
    options.setProtocol(Protocol['CTAP2']);
    options.setHasResidentKey(true);
    options.setHasUserVerification(true);
    options.setIsUserVerified(true);

    await driver.addVirtualAuthenticator(options);

    let residentCredential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(residentCredential);
    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
  });

  it('Add resident credential not supported when authenticator uses U2F protocol', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(true);

    await driver.addVirtualAuthenticator(options);

    let credential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(base64EncodedPK, 'base64').toString('binary'),
      0);

    try {
      await driver.addCredential(credential)
    }
    catch (e) {
      if (e instanceof InvalidArgumentError) {
        assert(true)
      }
      else {
        assert(false)
      }
    }
  });

  it('Create and add non residential key', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(false);

    await driver.addVirtualAuthenticator(options);

    let nonResidentCredential = new Credential().createNonResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      Buffer.from(base64EncodedPK, 'base64').toString('binary'),
      0);

    await driver.addCredential(nonResidentCredential);

    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
  });

  it('Get credential', async function() {
    options.setProtocol(Protocol['CTAP2']);
    options.setHasResidentKey(true);
    options.setHasUserVerification(true);
    options.setIsUserVerified(true);

    await driver.addVirtualAuthenticator(options);

    let residentCredential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(residentCredential);

    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
    assert.equal(BASE64_ENCODED_PK, Buffer.from(credentialList[0].privateKey(), 'binary').toString('base64'));
  });

  it('Remove all credentials', async function() {
    await driver.addVirtualAuthenticator(options);

    let nonResidentCredential = new Credential().createNonResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(nonResidentCredential);
    await driver.removeAllCredentials();

    let credentialList = await driver.getCredentials();
    assert.equal(0, credentialList.length);
  });

  it('Set is user verified', async function() {
    options.setIsUserVerified(true);
    assert.equal(options.getIsUserVerified(), true);
  });
});

Get Credential

Retorna a lista de credenciais que o autenticador possui.

    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasResidentKey(true)
      .setHasUserVerification(true)
      .setIsUserVerified(true);
    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
Show full example
package dev.selenium.interactions;

import dev.selenium.BaseChromeTest;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.InvalidArgumentException;
import org.openqa.selenium.virtualauthenticator.Credential;
import org.openqa.selenium.virtualauthenticator.HasVirtualAuthenticator;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticator;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;

public class VirtualAuthenticatorTest extends BaseChromeTest {

  /**
   * A pkcs#8 encoded encrypted RSA private key as a base64url string.
   */
  private final static String
    base64EncodedRsaPK =
    "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"
    + "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"
    + "GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"
    + "9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"
    + "vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"
    + "zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"
    + "XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"
    + "RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"
    + "QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"
    + "S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"
    + "ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"
    + "ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"
    + "OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"
    + "ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"
    + "hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"
    + "WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"
    + "NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"
    + "nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";

  private final static PKCS8EncodedKeySpec rsaPrivateKey =
    new PKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(base64EncodedRsaPK));

  // A pkcs#8 encoded unencrypted EC256 private key as a base64url string.
  String base64EncodedEC256PK =
    "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"
    + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"
    + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";

  PKCS8EncodedKeySpec ec256PrivateKey =
    new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));

  @Test
  public void testVirtualOptions() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true)
      .setHasUserVerification(true)
      .setIsUserConsenting(true)
      .setTransport(VirtualAuthenticatorOptions.Transport.USB)
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    Assertions.assertEquals(6, options.toMap().size());
  }

  @Test
  public void testCreateAuthenticator() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    List<Credential> credentialList = authenticator.getCredentials();

    Assertions.assertEquals(0, credentialList.size());
  }

  @Test
  public void testRemoveAuthenticator() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions();
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    ((HasVirtualAuthenticator) driver).removeVirtualAuthenticator(authenticator);

    Assertions.assertThrows(InvalidArgumentException.class, authenticator::getCredentials);
  }

  @Test
  public void testCreateAndAddResidentialKey() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasResidentKey(true)
      .setHasUserVerification(true)
      .setIsUserVerified(true);
    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
  }

  @Test
  public void testAddResidentCredentialNotSupportedWhenAuthenticatorUsesU2FProtocol() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(true);

    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    PKCS8EncodedKeySpec privateKey =
      new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential credential = Credential.createResidentCredential(
      credentialId, "localhost", privateKey, userHandle, /*signCount=*/0);

    Assertions.assertThrows(InvalidArgumentException.class,
                            () -> authenticator.addCredential(credential));
  }


  @Test
  public void testCreateAndAddNonResidentialKey() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    Credential nonResidentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", ec256PrivateKey, /*signCount=*/0);
    authenticator.addCredential(nonResidentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
  }

  @Test
  public void testGetCredential() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasResidentKey(true)
      .setHasUserVerification(true)
      .setIsUserVerified(true);
    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
    Assertions.assertArrayEquals(rsaPrivateKey.getEncoded(), credential.getPrivateKey().getEncoded());
  }

  @Test
  public void testRemoveCredential() {
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential credential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, 0);

    authenticator.addCredential(credential);

    authenticator.removeCredential(credentialId);
    Assertions.assertEquals(0, authenticator.getCredentials().size());
  }

  @Test
  public void testRemoveAllCredentials() {
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential residentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    authenticator.removeAllCredentials();
    Assertions.assertEquals(0, authenticator.getCredentials().size());
  }

  @Test
  public void testSetUserVerified() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true);

    Assertions.assertTrue((boolean) options.toMap().get("isUserVerified"));
  }
}
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(Protocol.CTAP2)
                .SetHasResidentKey(true)
                .SetHasUserVerification(true)
                .SetIsUserVerified(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);

            ((WebDriver)driver).AddCredential(residentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
Show full example
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.IdentityModel.Tokens;
using OpenQA.Selenium;
using OpenQA.Selenium.VirtualAuth;
using static OpenQA.Selenium.VirtualAuth.VirtualAuthenticatorOptions;
using System.Collections.Generic;
using System;

namespace SeleniumDocs.VirtualAuthentication
{
    [TestClass]
    public class VirtualAuthenticatorTest : BaseChromeTest
    {
        //A pkcs#8 encoded encrypted RSA private key as a base64 string.
        private static string base64EncodedRSAPK =
                "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"
              + "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"
              + "GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"
              + "9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"
              + "vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"
              + "zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"
              + "XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"
              + "RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"
              + "QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"
              + "S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"
              + "ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"
              + "ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"
              + "OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"
              + "ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"
              + "hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"
              + "WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"
              + "NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"
              + "nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";

        private static byte[] bytes = System.Convert.FromBase64String(base64EncodedRSAPK);
        private string base64EncodedPK = Base64UrlEncoder.Encode(bytes);

        // A pkcs#8 encoded unencrypted EC256 private key as a base64url string.
        private string base64EncodedEC256PK =
              "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"
              + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"
              + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";


        [TestMethod]
        public void VirtualOptionsShouldAllowSettingOptions()
        {
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true)
                .SetHasUserVerification(true)
                .SetIsUserConsenting(true)
                .SetTransport(VirtualAuthenticatorOptions.Transport.USB)
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            Assert.AreEqual(6, options.ToDictionary().Count);
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAuthenticator()
        {
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            // Register a virtual authenticator
            ((WebDriver)driver).AddVirtualAuthenticator(options);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();

            Assert.AreEqual(0, credentialList.Count);
        }


        [TestMethod]
        public void ShouldBeAbleToRemoveAuthenticator()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            String virtualAuthenticatorId = ((WebDriver)driver).AddVirtualAuthenticator(options);

            ((WebDriver)driver).RemoveVirtualAuthenticator(virtualAuthenticatorId);

            // Since the authenticator was removed, any operation using it will throw an error
            Assert.ThrowsException<InvalidOperationException>(() => ((WebDriver)driver).GetCredentials());
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAndAddResidentialKey()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(Protocol.CTAP2)
                .SetHasResidentKey(true)
                .SetHasUserVerification(true)
                .SetIsUserVerified(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);

            ((WebDriver)driver).AddCredential(residentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, credential.Id);
        }

        [TestMethod]
        public void ShouldNotAddResidentCredentialWhenAuthenticatorUsesU2FProtocol()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential credential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, userHandle, 0);

            Assert.ThrowsException<WebDriverArgumentException>(() => ((WebDriver)driver).AddCredential(credential));
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAndAddNonResidentKey()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, nonResidentCredential.Id);
        }

        [TestMethod]
        public void ShouldBeAbleToGetCredential()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(Protocol.CTAP2)
                .SetHasResidentKey(true)
                .SetHasUserVerification(true)
                .SetIsUserVerified(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);

            ((WebDriver)driver).AddCredential(residentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, residentCredential.Id);
            Assert.AreEqual(base64EncodedPK, credential.PrivateKey);
        }

        [TestMethod]
        public void ShouldBeAbleToRemoveCredential()
        {
            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveCredential(credentialId);

            Assert.AreEqual(0, ((WebDriver)driver).GetCredentials().Count);
        }


        [TestMethod]
        public void ShouldBeAbleToRemoveAllCredentias()
        {
            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveAllCredentials();

            Assert.AreEqual(0, ((WebDriver)driver).GetCredentials().Count);
        }

        [TestMethod]
        public void ShouldBeSetVerifiedOption()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true);

            Assert.IsTrue((bool)options.ToDictionary()["isUserVerified"]);
        }
    }
}
    credential_list = driver.get_credentials()
Show full example
import pytest
from base64 import urlsafe_b64decode, urlsafe_b64encode

from selenium.common.exceptions import InvalidArgumentException
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.virtual_authenticator import (
    Credential,
    VirtualAuthenticatorOptions,
)


BASE64__ENCODED_PK = '''
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV
oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ
FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq
GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0
+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM
8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD
/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ
5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe
pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol
L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d
xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi
uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8
K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct
lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa
9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
'''


@pytest.fixture(scope="module", autouse=True)
def driver():
    yield WebDriver()


def test_virtual_authenticator_options():
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True
    options.has_user_verification = True
    options.is_user_consenting = True
    options.transport = VirtualAuthenticatorOptions.Transport.USB
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    assert len(options.to_dict()) == 6


def test_add_authenticator(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # Get list of credentials
    credential_list = driver.get_credentials()

    assert len(credential_list) == 0


def test_remove_authenticator(driver):
    # Create default virtual authenticator option
    options = VirtualAuthenticatorOptions()

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # Remove virtual authenticator
    driver.remove_virtual_authenticator()
    assert driver.virtual_authenticator_id is None


def test_create_and_add_resident_key(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
    options.has_resident_key = True
    options.has_user_verification = True
    options.is_user_verified = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(resident_credential)

    # get list of all the registered credentials 
    credential_list = driver.get_credentials()
    assert len(credential_list) == 1


def test_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a  resident credential using above parameters
    credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)

    # Expect InvalidArgumentException 
    with pytest.raises(InvalidArgumentException):
        driver.add_credential(credential)


def test_create_and_add_non_resident_key(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Non Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a non resident credential using above parameters
    credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(credential)
    
    # get list of all the registered credentials 
    credential_list = driver.get_credentials()
    assert len(credential_list) == 1



def test_get_credential(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
    options.has_resident_key = True
    options.has_user_verfied = True
    options.is_user_verified = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)
    
    # add the credential created to virtual authenticator
    driver.add_credential(credential)

    # get list of all the registered credentials 
    credential_list = driver.get_credentials()

    assert len(credential_list) == 1
    assert credential_list[0].id == urlsafe_b64encode(credential_id).decode()


def test_remove_credential(driver):
    # Create default virtual authenticator options
    options = VirtualAuthenticatorOptions()

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Non Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a non resident credential using above parameters
    credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(credential)

    # remove the credential created from virtual authenticator
    driver.remove_credential(credential.id)

    # credential can also be removed using Byte Array
    # driver.remove_credential(credential_id) 

    assert len(driver.get_credentials()) == 0


def test_remove_all_credentials(driver):
    # Create default virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.has_resident_key = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)
    
    # add the credential created to virtual authenticator
    driver.add_credential(resident_credential)

    # remove all credentials in virtual authenticator
    driver.remove_all_credentials()

    assert len(driver.get_credentials()) == 0


def test_set_user_verified():
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True

    assert options.to_dict().get("isUserVerified") is True
    options.setProtocol(Protocol['CTAP2']);
    options.setHasResidentKey(true);
    options.setHasUserVerification(true);
    options.setIsUserVerified(true);

    await driver.addVirtualAuthenticator(options);

    let residentCredential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(residentCredential);

    let credentialList = await driver.getCredentials();
Show full example

const { Builder} = require("selenium-webdriver");
const { Credential, VirtualAuthenticatorOptions, Transport, Protocol } = require("selenium-webdriver/lib/virtual_authenticator");
const assert = require('assert')
const { InvalidArgumentError } = require("selenium-webdriver/lib/error");


describe('Virtual authenticator', function() {
  const BASE64_ENCODED_PK =
    "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr" +
    "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV" +
    "oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ" +
    "FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq" +
    "GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0" +
    "+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM" +
    "8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD" +
    "/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ" +
    "5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe" +
    "pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol" +
    "L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d" +
    "xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi" +
    "uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8" +
    "K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct" +
    "lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa" +
    "9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH" +
    "zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H" +
    "BYGpI8g==";

  const base64EncodedPK =
    "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q" +
    "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU" +
    "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";

  let options;
  let driver;

  before(async function() {
    options = new VirtualAuthenticatorOptions();
    driver = await new Builder().forBrowser('chrome').build();
  });

  after(async() => await driver.quit());

  function arraysEqual(array1, array2) {
    return (array1.length === array2.length &&
      array1.every((item) => array2.includes(item)) &&
      array2.every((item) => array1.includes(item)));
  }

  it('Register a virtual authenticator', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(false);

    // Register a virtual authenticator
    await driver.addVirtualAuthenticator(options);
    let credentialList = await driver.getCredentials();

    assert.equal(0, credentialList.length);
  });

  it('Remove authenticator', async function() {
    await driver.addVirtualAuthenticator(options);
    await driver.removeVirtualAuthenticator();

    // Since the authenticator was removed, any operation using it will throw an error
    try {
      await driver.getCredentials()
    }
    catch (e) {
      if (e instanceof InvalidArgumentError) {
        assert(true)
      }
      else {
        assert(false)
      }
    }
  });

  it('Createa and add residential key', async function() {
    options.setProtocol(Protocol['CTAP2']);
    options.setHasResidentKey(true);
    options.setHasUserVerification(true);
    options.setIsUserVerified(true);

    await driver.addVirtualAuthenticator(options);

    let residentCredential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(residentCredential);
    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
  });

  it('Add resident credential not supported when authenticator uses U2F protocol', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(true);

    await driver.addVirtualAuthenticator(options);

    let credential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(base64EncodedPK, 'base64').toString('binary'),
      0);

    try {
      await driver.addCredential(credential)
    }
    catch (e) {
      if (e instanceof InvalidArgumentError) {
        assert(true)
      }
      else {
        assert(false)
      }
    }
  });

  it('Create and add non residential key', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(false);

    await driver.addVirtualAuthenticator(options);

    let nonResidentCredential = new Credential().createNonResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      Buffer.from(base64EncodedPK, 'base64').toString('binary'),
      0);

    await driver.addCredential(nonResidentCredential);

    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
  });

  it('Get credential', async function() {
    options.setProtocol(Protocol['CTAP2']);
    options.setHasResidentKey(true);
    options.setHasUserVerification(true);
    options.setIsUserVerified(true);

    await driver.addVirtualAuthenticator(options);

    let residentCredential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(residentCredential);

    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
    assert.equal(BASE64_ENCODED_PK, Buffer.from(credentialList[0].privateKey(), 'binary').toString('base64'));
  });

  it('Remove all credentials', async function() {
    await driver.addVirtualAuthenticator(options);

    let nonResidentCredential = new Credential().createNonResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(nonResidentCredential);
    await driver.removeAllCredentials();

    let credentialList = await driver.getCredentials();
    assert.equal(0, credentialList.length);
  });

  it('Set is user verified', async function() {
    options.setIsUserVerified(true);
    assert.equal(options.getIsUserVerified(), true);
  });
});

Remove Credential

Remove a credencial do autenticador baseado na id da credencial passado.

            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveCredential(credentialId);
Show full example
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.IdentityModel.Tokens;
using OpenQA.Selenium;
using OpenQA.Selenium.VirtualAuth;
using static OpenQA.Selenium.VirtualAuth.VirtualAuthenticatorOptions;
using System.Collections.Generic;
using System;

namespace SeleniumDocs.VirtualAuthentication
{
    [TestClass]
    public class VirtualAuthenticatorTest : BaseChromeTest
    {
        //A pkcs#8 encoded encrypted RSA private key as a base64 string.
        private static string base64EncodedRSAPK =
                "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"
              + "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"
              + "GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"
              + "9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"
              + "vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"
              + "zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"
              + "XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"
              + "RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"
              + "QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"
              + "S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"
              + "ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"
              + "ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"
              + "OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"
              + "ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"
              + "hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"
              + "WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"
              + "NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"
              + "nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";

        private static byte[] bytes = System.Convert.FromBase64String(base64EncodedRSAPK);
        private string base64EncodedPK = Base64UrlEncoder.Encode(bytes);

        // A pkcs#8 encoded unencrypted EC256 private key as a base64url string.
        private string base64EncodedEC256PK =
              "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"
              + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"
              + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";


        [TestMethod]
        public void VirtualOptionsShouldAllowSettingOptions()
        {
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true)
                .SetHasUserVerification(true)
                .SetIsUserConsenting(true)
                .SetTransport(VirtualAuthenticatorOptions.Transport.USB)
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            Assert.AreEqual(6, options.ToDictionary().Count);
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAuthenticator()
        {
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            // Register a virtual authenticator
            ((WebDriver)driver).AddVirtualAuthenticator(options);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();

            Assert.AreEqual(0, credentialList.Count);
        }


        [TestMethod]
        public void ShouldBeAbleToRemoveAuthenticator()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            String virtualAuthenticatorId = ((WebDriver)driver).AddVirtualAuthenticator(options);

            ((WebDriver)driver).RemoveVirtualAuthenticator(virtualAuthenticatorId);

            // Since the authenticator was removed, any operation using it will throw an error
            Assert.ThrowsException<InvalidOperationException>(() => ((WebDriver)driver).GetCredentials());
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAndAddResidentialKey()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(Protocol.CTAP2)
                .SetHasResidentKey(true)
                .SetHasUserVerification(true)
                .SetIsUserVerified(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);

            ((WebDriver)driver).AddCredential(residentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, credential.Id);
        }

        [TestMethod]
        public void ShouldNotAddResidentCredentialWhenAuthenticatorUsesU2FProtocol()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential credential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, userHandle, 0);

            Assert.ThrowsException<WebDriverArgumentException>(() => ((WebDriver)driver).AddCredential(credential));
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAndAddNonResidentKey()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, nonResidentCredential.Id);
        }

        [TestMethod]
        public void ShouldBeAbleToGetCredential()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(Protocol.CTAP2)
                .SetHasResidentKey(true)
                .SetHasUserVerification(true)
                .SetIsUserVerified(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);

            ((WebDriver)driver).AddCredential(residentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, residentCredential.Id);
            Assert.AreEqual(base64EncodedPK, credential.PrivateKey);
        }

        [TestMethod]
        public void ShouldBeAbleToRemoveCredential()
        {
            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveCredential(credentialId);

            Assert.AreEqual(0, ((WebDriver)driver).GetCredentials().Count);
        }


        [TestMethod]
        public void ShouldBeAbleToRemoveAllCredentias()
        {
            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveAllCredentials();

            Assert.AreEqual(0, ((WebDriver)driver).GetCredentials().Count);
        }

        [TestMethod]
        public void ShouldBeSetVerifiedOption()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true);

            Assert.IsTrue((bool)options.ToDictionary()["isUserVerified"]);
        }
    }
}
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential credential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, 0);

    authenticator.addCredential(credential);

    authenticator.removeCredential(credentialId);
Show full example
package dev.selenium.interactions;

import dev.selenium.BaseChromeTest;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.InvalidArgumentException;
import org.openqa.selenium.virtualauthenticator.Credential;
import org.openqa.selenium.virtualauthenticator.HasVirtualAuthenticator;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticator;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;

public class VirtualAuthenticatorTest extends BaseChromeTest {

  /**
   * A pkcs#8 encoded encrypted RSA private key as a base64url string.
   */
  private final static String
    base64EncodedRsaPK =
    "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"
    + "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"
    + "GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"
    + "9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"
    + "vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"
    + "zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"
    + "XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"
    + "RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"
    + "QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"
    + "S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"
    + "ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"
    + "ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"
    + "OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"
    + "ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"
    + "hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"
    + "WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"
    + "NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"
    + "nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";

  private final static PKCS8EncodedKeySpec rsaPrivateKey =
    new PKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(base64EncodedRsaPK));

  // A pkcs#8 encoded unencrypted EC256 private key as a base64url string.
  String base64EncodedEC256PK =
    "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"
    + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"
    + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";

  PKCS8EncodedKeySpec ec256PrivateKey =
    new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));

  @Test
  public void testVirtualOptions() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true)
      .setHasUserVerification(true)
      .setIsUserConsenting(true)
      .setTransport(VirtualAuthenticatorOptions.Transport.USB)
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    Assertions.assertEquals(6, options.toMap().size());
  }

  @Test
  public void testCreateAuthenticator() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    List<Credential> credentialList = authenticator.getCredentials();

    Assertions.assertEquals(0, credentialList.size());
  }

  @Test
  public void testRemoveAuthenticator() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions();
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    ((HasVirtualAuthenticator) driver).removeVirtualAuthenticator(authenticator);

    Assertions.assertThrows(InvalidArgumentException.class, authenticator::getCredentials);
  }

  @Test
  public void testCreateAndAddResidentialKey() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasResidentKey(true)
      .setHasUserVerification(true)
      .setIsUserVerified(true);
    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
  }

  @Test
  public void testAddResidentCredentialNotSupportedWhenAuthenticatorUsesU2FProtocol() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(true);

    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    PKCS8EncodedKeySpec privateKey =
      new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential credential = Credential.createResidentCredential(
      credentialId, "localhost", privateKey, userHandle, /*signCount=*/0);

    Assertions.assertThrows(InvalidArgumentException.class,
                            () -> authenticator.addCredential(credential));
  }


  @Test
  public void testCreateAndAddNonResidentialKey() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    Credential nonResidentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", ec256PrivateKey, /*signCount=*/0);
    authenticator.addCredential(nonResidentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
  }

  @Test
  public void testGetCredential() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasResidentKey(true)
      .setHasUserVerification(true)
      .setIsUserVerified(true);
    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
    Assertions.assertArrayEquals(rsaPrivateKey.getEncoded(), credential.getPrivateKey().getEncoded());
  }

  @Test
  public void testRemoveCredential() {
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential credential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, 0);

    authenticator.addCredential(credential);

    authenticator.removeCredential(credentialId);
    Assertions.assertEquals(0, authenticator.getCredentials().size());
  }

  @Test
  public void testRemoveAllCredentials() {
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential residentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    authenticator.removeAllCredentials();
    Assertions.assertEquals(0, authenticator.getCredentials().size());
  }

  @Test
  public void testSetUserVerified() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true);

    Assertions.assertTrue((boolean) options.toMap().get("isUserVerified"));
  }
}
    driver.remove_credential(credential.id)
Show full example
import pytest
from base64 import urlsafe_b64decode, urlsafe_b64encode

from selenium.common.exceptions import InvalidArgumentException
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.virtual_authenticator import (
    Credential,
    VirtualAuthenticatorOptions,
)


BASE64__ENCODED_PK = '''
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV
oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ
FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq
GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0
+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM
8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD
/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ
5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe
pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol
L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d
xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi
uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8
K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct
lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa
9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
'''


@pytest.fixture(scope="module", autouse=True)
def driver():
    yield WebDriver()


def test_virtual_authenticator_options():
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True
    options.has_user_verification = True
    options.is_user_consenting = True
    options.transport = VirtualAuthenticatorOptions.Transport.USB
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    assert len(options.to_dict()) == 6


def test_add_authenticator(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # Get list of credentials
    credential_list = driver.get_credentials()

    assert len(credential_list) == 0


def test_remove_authenticator(driver):
    # Create default virtual authenticator option
    options = VirtualAuthenticatorOptions()

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # Remove virtual authenticator
    driver.remove_virtual_authenticator()
    assert driver.virtual_authenticator_id is None


def test_create_and_add_resident_key(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
    options.has_resident_key = True
    options.has_user_verification = True
    options.is_user_verified = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(resident_credential)

    # get list of all the registered credentials 
    credential_list = driver.get_credentials()
    assert len(credential_list) == 1


def test_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a  resident credential using above parameters
    credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)

    # Expect InvalidArgumentException 
    with pytest.raises(InvalidArgumentException):
        driver.add_credential(credential)


def test_create_and_add_non_resident_key(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Non Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a non resident credential using above parameters
    credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(credential)
    
    # get list of all the registered credentials 
    credential_list = driver.get_credentials()
    assert len(credential_list) == 1



def test_get_credential(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
    options.has_resident_key = True
    options.has_user_verfied = True
    options.is_user_verified = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)
    
    # add the credential created to virtual authenticator
    driver.add_credential(credential)

    # get list of all the registered credentials 
    credential_list = driver.get_credentials()

    assert len(credential_list) == 1
    assert credential_list[0].id == urlsafe_b64encode(credential_id).decode()


def test_remove_credential(driver):
    # Create default virtual authenticator options
    options = VirtualAuthenticatorOptions()

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Non Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a non resident credential using above parameters
    credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(credential)

    # remove the credential created from virtual authenticator
    driver.remove_credential(credential.id)

    # credential can also be removed using Byte Array
    # driver.remove_credential(credential_id) 

    assert len(driver.get_credentials()) == 0


def test_remove_all_credentials(driver):
    # Create default virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.has_resident_key = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)
    
    # add the credential created to virtual authenticator
    driver.add_credential(resident_credential)

    # remove all credentials in virtual authenticator
    driver.remove_all_credentials()

    assert len(driver.get_credentials()) == 0


def test_set_user_verified():
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True

    assert options.to_dict().get("isUserVerified") is True

Remove All Credentials

Remove todas as credenciais do autenticador.

    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential residentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    authenticator.removeAllCredentials();
Show full example
package dev.selenium.interactions;

import dev.selenium.BaseChromeTest;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.InvalidArgumentException;
import org.openqa.selenium.virtualauthenticator.Credential;
import org.openqa.selenium.virtualauthenticator.HasVirtualAuthenticator;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticator;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;

public class VirtualAuthenticatorTest extends BaseChromeTest {

  /**
   * A pkcs#8 encoded encrypted RSA private key as a base64url string.
   */
  private final static String
    base64EncodedRsaPK =
    "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"
    + "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"
    + "GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"
    + "9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"
    + "vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"
    + "zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"
    + "XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"
    + "RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"
    + "QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"
    + "S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"
    + "ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"
    + "ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"
    + "OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"
    + "ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"
    + "hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"
    + "WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"
    + "NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"
    + "nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";

  private final static PKCS8EncodedKeySpec rsaPrivateKey =
    new PKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(base64EncodedRsaPK));

  // A pkcs#8 encoded unencrypted EC256 private key as a base64url string.
  String base64EncodedEC256PK =
    "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"
    + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"
    + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";

  PKCS8EncodedKeySpec ec256PrivateKey =
    new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));

  @Test
  public void testVirtualOptions() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true)
      .setHasUserVerification(true)
      .setIsUserConsenting(true)
      .setTransport(VirtualAuthenticatorOptions.Transport.USB)
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    Assertions.assertEquals(6, options.toMap().size());
  }

  @Test
  public void testCreateAuthenticator() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    List<Credential> credentialList = authenticator.getCredentials();

    Assertions.assertEquals(0, credentialList.size());
  }

  @Test
  public void testRemoveAuthenticator() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions();
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    ((HasVirtualAuthenticator) driver).removeVirtualAuthenticator(authenticator);

    Assertions.assertThrows(InvalidArgumentException.class, authenticator::getCredentials);
  }

  @Test
  public void testCreateAndAddResidentialKey() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasResidentKey(true)
      .setHasUserVerification(true)
      .setIsUserVerified(true);
    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
  }

  @Test
  public void testAddResidentCredentialNotSupportedWhenAuthenticatorUsesU2FProtocol() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(true);

    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    PKCS8EncodedKeySpec privateKey =
      new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential credential = Credential.createResidentCredential(
      credentialId, "localhost", privateKey, userHandle, /*signCount=*/0);

    Assertions.assertThrows(InvalidArgumentException.class,
                            () -> authenticator.addCredential(credential));
  }


  @Test
  public void testCreateAndAddNonResidentialKey() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    Credential nonResidentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", ec256PrivateKey, /*signCount=*/0);
    authenticator.addCredential(nonResidentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
  }

  @Test
  public void testGetCredential() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasResidentKey(true)
      .setHasUserVerification(true)
      .setIsUserVerified(true);
    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
    Assertions.assertArrayEquals(rsaPrivateKey.getEncoded(), credential.getPrivateKey().getEncoded());
  }

  @Test
  public void testRemoveCredential() {
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential credential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, 0);

    authenticator.addCredential(credential);

    authenticator.removeCredential(credentialId);
    Assertions.assertEquals(0, authenticator.getCredentials().size());
  }

  @Test
  public void testRemoveAllCredentials() {
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential residentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    authenticator.removeAllCredentials();
    Assertions.assertEquals(0, authenticator.getCredentials().size());
  }

  @Test
  public void testSetUserVerified() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true);

    Assertions.assertTrue((boolean) options.toMap().get("isUserVerified"));
  }
}
            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveAllCredentials();
Show full example
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.IdentityModel.Tokens;
using OpenQA.Selenium;
using OpenQA.Selenium.VirtualAuth;
using static OpenQA.Selenium.VirtualAuth.VirtualAuthenticatorOptions;
using System.Collections.Generic;
using System;

namespace SeleniumDocs.VirtualAuthentication
{
    [TestClass]
    public class VirtualAuthenticatorTest : BaseChromeTest
    {
        //A pkcs#8 encoded encrypted RSA private key as a base64 string.
        private static string base64EncodedRSAPK =
                "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"
              + "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"
              + "GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"
              + "9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"
              + "vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"
              + "zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"
              + "XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"
              + "RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"
              + "QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"
              + "S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"
              + "ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"
              + "ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"
              + "OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"
              + "ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"
              + "hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"
              + "WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"
              + "NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"
              + "nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";

        private static byte[] bytes = System.Convert.FromBase64String(base64EncodedRSAPK);
        private string base64EncodedPK = Base64UrlEncoder.Encode(bytes);

        // A pkcs#8 encoded unencrypted EC256 private key as a base64url string.
        private string base64EncodedEC256PK =
              "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"
              + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"
              + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";


        [TestMethod]
        public void VirtualOptionsShouldAllowSettingOptions()
        {
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true)
                .SetHasUserVerification(true)
                .SetIsUserConsenting(true)
                .SetTransport(VirtualAuthenticatorOptions.Transport.USB)
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            Assert.AreEqual(6, options.ToDictionary().Count);
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAuthenticator()
        {
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            // Register a virtual authenticator
            ((WebDriver)driver).AddVirtualAuthenticator(options);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();

            Assert.AreEqual(0, credentialList.Count);
        }


        [TestMethod]
        public void ShouldBeAbleToRemoveAuthenticator()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            String virtualAuthenticatorId = ((WebDriver)driver).AddVirtualAuthenticator(options);

            ((WebDriver)driver).RemoveVirtualAuthenticator(virtualAuthenticatorId);

            // Since the authenticator was removed, any operation using it will throw an error
            Assert.ThrowsException<InvalidOperationException>(() => ((WebDriver)driver).GetCredentials());
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAndAddResidentialKey()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(Protocol.CTAP2)
                .SetHasResidentKey(true)
                .SetHasUserVerification(true)
                .SetIsUserVerified(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);

            ((WebDriver)driver).AddCredential(residentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, credential.Id);
        }

        [TestMethod]
        public void ShouldNotAddResidentCredentialWhenAuthenticatorUsesU2FProtocol()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential credential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, userHandle, 0);

            Assert.ThrowsException<WebDriverArgumentException>(() => ((WebDriver)driver).AddCredential(credential));
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAndAddNonResidentKey()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, nonResidentCredential.Id);
        }

        [TestMethod]
        public void ShouldBeAbleToGetCredential()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(Protocol.CTAP2)
                .SetHasResidentKey(true)
                .SetHasUserVerification(true)
                .SetIsUserVerified(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);

            ((WebDriver)driver).AddCredential(residentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, residentCredential.Id);
            Assert.AreEqual(base64EncodedPK, credential.PrivateKey);
        }

        [TestMethod]
        public void ShouldBeAbleToRemoveCredential()
        {
            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveCredential(credentialId);

            Assert.AreEqual(0, ((WebDriver)driver).GetCredentials().Count);
        }


        [TestMethod]
        public void ShouldBeAbleToRemoveAllCredentias()
        {
            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveAllCredentials();

            Assert.AreEqual(0, ((WebDriver)driver).GetCredentials().Count);
        }

        [TestMethod]
        public void ShouldBeSetVerifiedOption()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true);

            Assert.IsTrue((bool)options.ToDictionary()["isUserVerified"]);
        }
    }
}
    driver.remove_all_credentials()
Show full example
import pytest
from base64 import urlsafe_b64decode, urlsafe_b64encode

from selenium.common.exceptions import InvalidArgumentException
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.virtual_authenticator import (
    Credential,
    VirtualAuthenticatorOptions,
)


BASE64__ENCODED_PK = '''
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV
oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ
FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq
GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0
+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM
8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD
/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ
5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe
pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol
L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d
xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi
uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8
K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct
lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa
9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
'''


@pytest.fixture(scope="module", autouse=True)
def driver():
    yield WebDriver()


def test_virtual_authenticator_options():
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True
    options.has_user_verification = True
    options.is_user_consenting = True
    options.transport = VirtualAuthenticatorOptions.Transport.USB
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    assert len(options.to_dict()) == 6


def test_add_authenticator(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # Get list of credentials
    credential_list = driver.get_credentials()

    assert len(credential_list) == 0


def test_remove_authenticator(driver):
    # Create default virtual authenticator option
    options = VirtualAuthenticatorOptions()

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # Remove virtual authenticator
    driver.remove_virtual_authenticator()
    assert driver.virtual_authenticator_id is None


def test_create_and_add_resident_key(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
    options.has_resident_key = True
    options.has_user_verification = True
    options.is_user_verified = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(resident_credential)

    # get list of all the registered credentials 
    credential_list = driver.get_credentials()
    assert len(credential_list) == 1


def test_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a  resident credential using above parameters
    credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)

    # Expect InvalidArgumentException 
    with pytest.raises(InvalidArgumentException):
        driver.add_credential(credential)


def test_create_and_add_non_resident_key(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Non Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a non resident credential using above parameters
    credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(credential)
    
    # get list of all the registered credentials 
    credential_list = driver.get_credentials()
    assert len(credential_list) == 1



def test_get_credential(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
    options.has_resident_key = True
    options.has_user_verfied = True
    options.is_user_verified = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)
    
    # add the credential created to virtual authenticator
    driver.add_credential(credential)

    # get list of all the registered credentials 
    credential_list = driver.get_credentials()

    assert len(credential_list) == 1
    assert credential_list[0].id == urlsafe_b64encode(credential_id).decode()


def test_remove_credential(driver):
    # Create default virtual authenticator options
    options = VirtualAuthenticatorOptions()

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Non Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a non resident credential using above parameters
    credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(credential)

    # remove the credential created from virtual authenticator
    driver.remove_credential(credential.id)

    # credential can also be removed using Byte Array
    # driver.remove_credential(credential_id) 

    assert len(driver.get_credentials()) == 0


def test_remove_all_credentials(driver):
    # Create default virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.has_resident_key = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)
    
    # add the credential created to virtual authenticator
    driver.add_credential(resident_credential)

    # remove all credentials in virtual authenticator
    driver.remove_all_credentials()

    assert len(driver.get_credentials()) == 0


def test_set_user_verified():
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True

    assert options.to_dict().get("isUserVerified") is True
    await driver.addVirtualAuthenticator(options);

    let nonResidentCredential = new Credential().createNonResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(nonResidentCredential);
    await driver.removeAllCredentials();
Show full example

const { Builder} = require("selenium-webdriver");
const { Credential, VirtualAuthenticatorOptions, Transport, Protocol } = require("selenium-webdriver/lib/virtual_authenticator");
const assert = require('assert')
const { InvalidArgumentError } = require("selenium-webdriver/lib/error");


describe('Virtual authenticator', function() {
  const BASE64_ENCODED_PK =
    "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr" +
    "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV" +
    "oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ" +
    "FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq" +
    "GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0" +
    "+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM" +
    "8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD" +
    "/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ" +
    "5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe" +
    "pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol" +
    "L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d" +
    "xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi" +
    "uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8" +
    "K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct" +
    "lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa" +
    "9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH" +
    "zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H" +
    "BYGpI8g==";

  const base64EncodedPK =
    "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q" +
    "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU" +
    "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";

  let options;
  let driver;

  before(async function() {
    options = new VirtualAuthenticatorOptions();
    driver = await new Builder().forBrowser('chrome').build();
  });

  after(async() => await driver.quit());

  function arraysEqual(array1, array2) {
    return (array1.length === array2.length &&
      array1.every((item) => array2.includes(item)) &&
      array2.every((item) => array1.includes(item)));
  }

  it('Register a virtual authenticator', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(false);

    // Register a virtual authenticator
    await driver.addVirtualAuthenticator(options);
    let credentialList = await driver.getCredentials();

    assert.equal(0, credentialList.length);
  });

  it('Remove authenticator', async function() {
    await driver.addVirtualAuthenticator(options);
    await driver.removeVirtualAuthenticator();

    // Since the authenticator was removed, any operation using it will throw an error
    try {
      await driver.getCredentials()
    }
    catch (e) {
      if (e instanceof InvalidArgumentError) {
        assert(true)
      }
      else {
        assert(false)
      }
    }
  });

  it('Createa and add residential key', async function() {
    options.setProtocol(Protocol['CTAP2']);
    options.setHasResidentKey(true);
    options.setHasUserVerification(true);
    options.setIsUserVerified(true);

    await driver.addVirtualAuthenticator(options);

    let residentCredential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(residentCredential);
    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
  });

  it('Add resident credential not supported when authenticator uses U2F protocol', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(true);

    await driver.addVirtualAuthenticator(options);

    let credential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(base64EncodedPK, 'base64').toString('binary'),
      0);

    try {
      await driver.addCredential(credential)
    }
    catch (e) {
      if (e instanceof InvalidArgumentError) {
        assert(true)
      }
      else {
        assert(false)
      }
    }
  });

  it('Create and add non residential key', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(false);

    await driver.addVirtualAuthenticator(options);

    let nonResidentCredential = new Credential().createNonResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      Buffer.from(base64EncodedPK, 'base64').toString('binary'),
      0);

    await driver.addCredential(nonResidentCredential);

    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
  });

  it('Get credential', async function() {
    options.setProtocol(Protocol['CTAP2']);
    options.setHasResidentKey(true);
    options.setHasUserVerification(true);
    options.setIsUserVerified(true);

    await driver.addVirtualAuthenticator(options);

    let residentCredential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(residentCredential);

    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
    assert.equal(BASE64_ENCODED_PK, Buffer.from(credentialList[0].privateKey(), 'binary').toString('base64'));
  });

  it('Remove all credentials', async function() {
    await driver.addVirtualAuthenticator(options);

    let nonResidentCredential = new Credential().createNonResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(nonResidentCredential);
    await driver.removeAllCredentials();

    let credentialList = await driver.getCredentials();
    assert.equal(0, credentialList.length);
  });

  it('Set is user verified', async function() {
    options.setIsUserVerified(true);
    assert.equal(options.getIsUserVerified(), true);
  });
});

Set User Verified

Diz se o autenticador simulará sucesso ou falha na verificação de usuário.

    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true);
Show full example
package dev.selenium.interactions;

import dev.selenium.BaseChromeTest;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.InvalidArgumentException;
import org.openqa.selenium.virtualauthenticator.Credential;
import org.openqa.selenium.virtualauthenticator.HasVirtualAuthenticator;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticator;
import org.openqa.selenium.virtualauthenticator.VirtualAuthenticatorOptions;

public class VirtualAuthenticatorTest extends BaseChromeTest {

  /**
   * A pkcs#8 encoded encrypted RSA private key as a base64url string.
   */
  private final static String
    base64EncodedRsaPK =
    "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"
    + "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"
    + "GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"
    + "9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"
    + "vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"
    + "zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"
    + "XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"
    + "RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"
    + "QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"
    + "S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"
    + "ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"
    + "ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"
    + "OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"
    + "ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"
    + "hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"
    + "WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"
    + "NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"
    + "nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";

  private final static PKCS8EncodedKeySpec rsaPrivateKey =
    new PKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(base64EncodedRsaPK));

  // A pkcs#8 encoded unencrypted EC256 private key as a base64url string.
  String base64EncodedEC256PK =
    "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"
    + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"
    + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";

  PKCS8EncodedKeySpec ec256PrivateKey =
    new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));

  @Test
  public void testVirtualOptions() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true)
      .setHasUserVerification(true)
      .setIsUserConsenting(true)
      .setTransport(VirtualAuthenticatorOptions.Transport.USB)
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    Assertions.assertEquals(6, options.toMap().size());
  }

  @Test
  public void testCreateAuthenticator() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    List<Credential> credentialList = authenticator.getCredentials();

    Assertions.assertEquals(0, credentialList.size());
  }

  @Test
  public void testRemoveAuthenticator() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions();
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    ((HasVirtualAuthenticator) driver).removeVirtualAuthenticator(authenticator);

    Assertions.assertThrows(InvalidArgumentException.class, authenticator::getCredentials);
  }

  @Test
  public void testCreateAndAddResidentialKey() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasResidentKey(true)
      .setHasUserVerification(true)
      .setIsUserVerified(true);
    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
  }

  @Test
  public void testAddResidentCredentialNotSupportedWhenAuthenticatorUsesU2FProtocol() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(true);

    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    PKCS8EncodedKeySpec privateKey =
      new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedEC256PK));

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential credential = Credential.createResidentCredential(
      credentialId, "localhost", privateKey, userHandle, /*signCount=*/0);

    Assertions.assertThrows(InvalidArgumentException.class,
                            () -> authenticator.addCredential(credential));
  }


  @Test
  public void testCreateAndAddNonResidentialKey() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
      .setHasResidentKey(false);

    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    Credential nonResidentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", ec256PrivateKey, /*signCount=*/0);
    authenticator.addCredential(nonResidentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
  }

  @Test
  public void testGetCredential() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasResidentKey(true)
      .setHasUserVerification(true)
      .setIsUserVerified(true);
    VirtualAuthenticator authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);

    byte[] credentialId = {1, 2, 3, 4};
    byte[] userHandle = {1};
    Credential residentCredential = Credential.createResidentCredential(
      credentialId, "localhost", rsaPrivateKey, userHandle, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    List<Credential> credentialList = authenticator.getCredentials();
    Assertions.assertEquals(1, credentialList.size());

    Credential credential = credentialList.get(0);
    Assertions.assertArrayEquals(credentialId, credential.getId());
    Assertions.assertArrayEquals(rsaPrivateKey.getEncoded(), credential.getPrivateKey().getEncoded());
  }

  @Test
  public void testRemoveCredential() {
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential credential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, 0);

    authenticator.addCredential(credential);

    authenticator.removeCredential(credentialId);
    Assertions.assertEquals(0, authenticator.getCredentials().size());
  }

  @Test
  public void testRemoveAllCredentials() {
    VirtualAuthenticator authenticator =
      ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(new VirtualAuthenticatorOptions());

    byte[] credentialId = {1, 2, 3, 4};
    Credential residentCredential = Credential.createNonResidentCredential(
      credentialId, "localhost", rsaPrivateKey, /*signCount=*/0);

    authenticator.addCredential(residentCredential);

    authenticator.removeAllCredentials();
    Assertions.assertEquals(0, authenticator.getCredentials().size());
  }

  @Test
  public void testSetUserVerified() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true);

    Assertions.assertTrue((boolean) options.toMap().get("isUserVerified"));
  }
}
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true);
Show full example
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.IdentityModel.Tokens;
using OpenQA.Selenium;
using OpenQA.Selenium.VirtualAuth;
using static OpenQA.Selenium.VirtualAuth.VirtualAuthenticatorOptions;
using System.Collections.Generic;
using System;

namespace SeleniumDocs.VirtualAuthentication
{
    [TestClass]
    public class VirtualAuthenticatorTest : BaseChromeTest
    {
        //A pkcs#8 encoded encrypted RSA private key as a base64 string.
        private static string base64EncodedRSAPK =
                "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr"
              + "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuB"
              + "GVoPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi"
              + "9AyQFR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1P"
              + "vSqXlqGjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsui"
              + "zAgyPuQ0+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/"
              + "XYY22ecYxM8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtib"
              + "RXz5FcNld9MgD/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swyko"
              + "QKBgQD8hCsp6FIQ5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMC"
              + "S6S64/qzZEqijLCqepwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnK"
              + "ws1t5GapfE1rmC/h4olL2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63"
              + "ojKjegxHIyYDKRZNVUR/dxAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM /r8PSflNHQKBgDnWgBh6OQncChPUl"
              + "OLv9FMZPR1ZOfqLCYrjYEqiuzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8V"
              + "ASOmqM1ml667axeZDIR867ZG8K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6B"
              + "hZC7z8mx+pnJODU3cYukxv3WTctlUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJw"
              + "WkBwYADmkfTRmHDvqzQSSvoC2S7aa9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KI"
              + "NpLwcR8fqaYOdAHWWz636osVEqosRrHzJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fB"
              + "nzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4HBYGpI8g==";

        private static byte[] bytes = System.Convert.FromBase64String(base64EncodedRSAPK);
        private string base64EncodedPK = Base64UrlEncoder.Encode(bytes);

        // A pkcs#8 encoded unencrypted EC256 private key as a base64url string.
        private string base64EncodedEC256PK =
              "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q"
              + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU"
              + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";


        [TestMethod]
        public void VirtualOptionsShouldAllowSettingOptions()
        {
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true)
                .SetHasUserVerification(true)
                .SetIsUserConsenting(true)
                .SetTransport(VirtualAuthenticatorOptions.Transport.USB)
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            Assert.AreEqual(6, options.ToDictionary().Count);
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAuthenticator()
        {
            // Create virtual authenticator options
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            // Register a virtual authenticator
            ((WebDriver)driver).AddVirtualAuthenticator(options);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();

            Assert.AreEqual(0, credentialList.Count);
        }


        [TestMethod]
        public void ShouldBeAbleToRemoveAuthenticator()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            String virtualAuthenticatorId = ((WebDriver)driver).AddVirtualAuthenticator(options);

            ((WebDriver)driver).RemoveVirtualAuthenticator(virtualAuthenticatorId);

            // Since the authenticator was removed, any operation using it will throw an error
            Assert.ThrowsException<InvalidOperationException>(() => ((WebDriver)driver).GetCredentials());
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAndAddResidentialKey()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(Protocol.CTAP2)
                .SetHasResidentKey(true)
                .SetHasUserVerification(true)
                .SetIsUserVerified(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);

            ((WebDriver)driver).AddCredential(residentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, credential.Id);
        }

        [TestMethod]
        public void ShouldNotAddResidentCredentialWhenAuthenticatorUsesU2FProtocol()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential credential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, userHandle, 0);

            Assert.ThrowsException<WebDriverArgumentException>(() => ((WebDriver)driver).AddCredential(credential));
        }

        [TestMethod]
        public void ShouldBeAbleToCreateAndAddNonResidentKey()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(VirtualAuthenticatorOptions.Protocol.U2F)
                .SetHasResidentKey(false);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, nonResidentCredential.Id);
        }

        [TestMethod]
        public void ShouldBeAbleToGetCredential()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetProtocol(Protocol.CTAP2)
                .SetHasResidentKey(true)
                .SetHasUserVerification(true)
                .SetIsUserVerified(true);

            ((WebDriver)driver).AddVirtualAuthenticator(options);

            byte[] credentialId = { 1, 2, 3, 4 };
            byte[] userHandle = { 1 };

            Credential residentCredential = Credential.CreateResidentCredential(
              credentialId, "localhost", base64EncodedPK, userHandle, 0);

            ((WebDriver)driver).AddCredential(residentCredential);

            List<Credential> credentialList = ((WebDriver)driver).GetCredentials();
            Assert.AreEqual(1, credentialList.Count);

            Credential credential = credentialList[0];
            CollectionAssert.AreEqual(credentialId, residentCredential.Id);
            Assert.AreEqual(base64EncodedPK, credential.PrivateKey);
        }

        [TestMethod]
        public void ShouldBeAbleToRemoveCredential()
        {
            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveCredential(credentialId);

            Assert.AreEqual(0, ((WebDriver)driver).GetCredentials().Count);
        }


        [TestMethod]
        public void ShouldBeAbleToRemoveAllCredentias()
        {
            ((WebDriver)driver).AddVirtualAuthenticator(new VirtualAuthenticatorOptions());

            byte[] credentialId = { 1, 2, 3, 4 };

            Credential nonResidentCredential = Credential.CreateNonResidentCredential(
              credentialId, "localhost", base64EncodedEC256PK, 0);

            ((WebDriver)driver).AddCredential(nonResidentCredential);

            ((WebDriver)driver).RemoveAllCredentials();

            Assert.AreEqual(0, ((WebDriver)driver).GetCredentials().Count);
        }

        [TestMethod]
        public void ShouldBeSetVerifiedOption()
        {
            VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
                .SetIsUserVerified(true);

            Assert.IsTrue((bool)options.ToDictionary()["isUserVerified"]);
        }
    }
}
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True
Show full example
import pytest
from base64 import urlsafe_b64decode, urlsafe_b64encode

from selenium.common.exceptions import InvalidArgumentException
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.virtual_authenticator import (
    Credential,
    VirtualAuthenticatorOptions,
)


BASE64__ENCODED_PK = '''
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr
MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV
oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ
FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq
GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0
+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM
8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD
/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ
5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe
pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol
L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d
xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi
uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8
K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct
lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa
9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH
zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H
BYGpI8g==
'''


@pytest.fixture(scope="module", autouse=True)
def driver():
    yield WebDriver()


def test_virtual_authenticator_options():
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True
    options.has_user_verification = True
    options.is_user_consenting = True
    options.transport = VirtualAuthenticatorOptions.Transport.USB
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    assert len(options.to_dict()) == 6


def test_add_authenticator(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # Get list of credentials
    credential_list = driver.get_credentials()

    assert len(credential_list) == 0


def test_remove_authenticator(driver):
    # Create default virtual authenticator option
    options = VirtualAuthenticatorOptions()

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # Remove virtual authenticator
    driver.remove_virtual_authenticator()
    assert driver.virtual_authenticator_id is None


def test_create_and_add_resident_key(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
    options.has_resident_key = True
    options.has_user_verification = True
    options.is_user_verified = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(resident_credential)

    # get list of all the registered credentials 
    credential_list = driver.get_credentials()
    assert len(credential_list) == 1


def test_add_resident_credential_not_supported_when_authenticator_uses_u2f_protocol(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a  resident credential using above parameters
    credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)

    # Expect InvalidArgumentException 
    with pytest.raises(InvalidArgumentException):
        driver.add_credential(credential)


def test_create_and_add_non_resident_key(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.U2F
    options.has_resident_key = False

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Non Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a non resident credential using above parameters
    credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(credential)
    
    # get list of all the registered credentials 
    credential_list = driver.get_credentials()
    assert len(credential_list) == 1



def test_get_credential(driver):
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.protocol = VirtualAuthenticatorOptions.Protocol.CTAP2
    options.has_resident_key = True
    options.has_user_verfied = True
    options.is_user_verified = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)
    
    # add the credential created to virtual authenticator
    driver.add_credential(credential)

    # get list of all the registered credentials 
    credential_list = driver.get_credentials()

    assert len(credential_list) == 1
    assert credential_list[0].id == urlsafe_b64encode(credential_id).decode()


def test_remove_credential(driver):
    # Create default virtual authenticator options
    options = VirtualAuthenticatorOptions()

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Non Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a non resident credential using above parameters
    credential = Credential.create_non_resident_credential(credential_id, rp_id, privatekey, sign_count)

    # add the credential created to virtual authenticator
    driver.add_credential(credential)

    # remove the credential created from virtual authenticator
    driver.remove_credential(credential.id)

    # credential can also be removed using Byte Array
    # driver.remove_credential(credential_id) 

    assert len(driver.get_credentials()) == 0


def test_remove_all_credentials(driver):
    # Create default virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.has_resident_key = True

    # Register a virtual authenticator
    driver.add_virtual_authenticator(options)

    # parameters for Resident Credential
    credential_id = bytearray({1, 2, 3, 4})
    rp_id = "localhost"
    user_handle = bytearray({1})
    privatekey = urlsafe_b64decode(BASE64__ENCODED_PK)
    sign_count = 0

    # create a resident credential using above parameters
    resident_credential = Credential.create_resident_credential(credential_id, rp_id, user_handle, privatekey, sign_count)
    
    # add the credential created to virtual authenticator
    driver.add_credential(resident_credential)

    # remove all credentials in virtual authenticator
    driver.remove_all_credentials()

    assert len(driver.get_credentials()) == 0


def test_set_user_verified():
    # Create virtual authenticator options
    options = VirtualAuthenticatorOptions()
    options.is_user_verified = True

    assert options.to_dict().get("isUserVerified") is True
    options.setIsUserVerified(true);
Show full example

const { Builder} = require("selenium-webdriver");
const { Credential, VirtualAuthenticatorOptions, Transport, Protocol } = require("selenium-webdriver/lib/virtual_authenticator");
const assert = require('assert')
const { InvalidArgumentError } = require("selenium-webdriver/lib/error");


describe('Virtual authenticator', function() {
  const BASE64_ENCODED_PK =
    "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDbBOu5Lhs4vpowbCnmCyLUpIE7JM9sm9QXzye2G+jr+Kr" +
    "MsinWohEce47BFPJlTaDzHSvOW2eeunBO89ZcvvVc8RLz4qyQ8rO98xS1jtgqi1NcBPETDrtzthODu/gd0sjB2Tk3TLuBGV" +
    "oPXt54a+Oo4JbBJ6h3s0+5eAfGplCbSNq6hN3Jh9YOTw5ZA6GCEy5l8zBaOgjXytd2v2OdSVoEDNiNQRkjJd2rmS2oi9AyQ" +
    "FR3B7BrPSiDlCcITZFOWgLF5C31Wp/PSHwQhlnh7/6YhnE2y9tzsUvzx0wJXrBADW13+oMxrneDK3WGbxTNYgIi1PvSqXlq" +
    "GjHtCK+R2QkXAgMBAAECggEAVc6bu7VAnP6v0gDOeX4razv4FX/adCao9ZsHZ+WPX8PQxtmWYqykH5CY4TSfsuizAgyPuQ0" +
    "+j4Vjssr9VODLqFoanspT6YXsvaKanncUYbasNgUJnfnLnw3an2XpU2XdmXTNYckCPRX9nsAAURWT3/n9ljc/XYY22ecYxM" +
    "8sDWnHu2uKZ1B7M3X60bQYL5T/lVXkKdD6xgSNLeP4AkRx0H4egaop68hoW8FIwmDPVWYVAvo8etzWCtibRXz5FcNld9MgD" +
    "/Ai7ycKy4Q1KhX5GBFI79MVVaHkSQfxPHpr7/XcmpQOEAr+BMPon4s4vnKqAGdGB3j/E3d/+4F2swykoQKBgQD8hCsp6FIQ" +
    "5umJlk9/j/nGsMl85LgLaNVYpWlPRKPc54YNumtvj5vx1BG+zMbT7qIE3nmUPTCHP7qb5ERZG4CdMCS6S64/qzZEqijLCqe" +
    "pwj6j4fV5SyPWEcpxf6ehNdmcfgzVB3Wolfwh1ydhx/96L1jHJcTKchdJJzlfTvq8wwKBgQDeCnKws1t5GapfE1rmC/h4ol" +
    "L2qZTth9oQmbrXYohVnoqNFslDa43ePZwL9Jmd9kYb0axOTNMmyrP0NTj41uCfgDS0cJnNTc63ojKjegxHIyYDKRZNVUR/d" +
    "xAYB/vPfBYZUS7M89pO6LLsHhzS3qpu3/hppo/Uc/AM/r8PSflNHQKBgDnWgBh6OQncChPUlOLv9FMZPR1ZOfqLCYrjYEqi" +
    "uzGm6iKM13zXFO4AGAxu1P/IAd5BovFcTpg79Z8tWqZaUUwvscnl+cRlj+mMXAmdqCeO8VASOmqM1ml667axeZDIR867ZG8" +
    "K5V029Wg+4qtX5uFypNAAi6GfHkxIKrD04yOHAoGACdh4wXESi0oiDdkz3KOHPwIjn6BhZC7z8mx+pnJODU3cYukxv3WTct" +
    "lUhAsyjJiQ/0bK1yX87ulqFVgO0Knmh+wNajrb9wiONAJTMICG7tiWJOm7fW5cfTJwWkBwYADmkfTRmHDvqzQSSvoC2S7aa" +
    "9QulbC3C/qgGFNrcWgcT9kCgYAZTa1P9bFCDU7hJc2mHwJwAW7/FQKEJg8SL33KINpLwcR8fqaYOdAHWWz636osVEqosRrH" +
    "zJOGpf9x2RSWzQJ+dq8+6fACgfFZOVpN644+sAHfNPAI/gnNKU5OfUv+eav8fBnzlf1A3y3GIkyMyzFN3DE7e0n/lyqxE4H" +
    "BYGpI8g==";

  const base64EncodedPK =
    "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q" +
    "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU" +
    "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB";

  let options;
  let driver;

  before(async function() {
    options = new VirtualAuthenticatorOptions();
    driver = await new Builder().forBrowser('chrome').build();
  });

  after(async() => await driver.quit());

  function arraysEqual(array1, array2) {
    return (array1.length === array2.length &&
      array1.every((item) => array2.includes(item)) &&
      array2.every((item) => array1.includes(item)));
  }

  it('Register a virtual authenticator', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(false);

    // Register a virtual authenticator
    await driver.addVirtualAuthenticator(options);
    let credentialList = await driver.getCredentials();

    assert.equal(0, credentialList.length);
  });

  it('Remove authenticator', async function() {
    await driver.addVirtualAuthenticator(options);
    await driver.removeVirtualAuthenticator();

    // Since the authenticator was removed, any operation using it will throw an error
    try {
      await driver.getCredentials()
    }
    catch (e) {
      if (e instanceof InvalidArgumentError) {
        assert(true)
      }
      else {
        assert(false)
      }
    }
  });

  it('Createa and add residential key', async function() {
    options.setProtocol(Protocol['CTAP2']);
    options.setHasResidentKey(true);
    options.setHasUserVerification(true);
    options.setIsUserVerified(true);

    await driver.addVirtualAuthenticator(options);

    let residentCredential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(residentCredential);
    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
  });

  it('Add resident credential not supported when authenticator uses U2F protocol', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(true);

    await driver.addVirtualAuthenticator(options);

    let credential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(base64EncodedPK, 'base64').toString('binary'),
      0);

    try {
      await driver.addCredential(credential)
    }
    catch (e) {
      if (e instanceof InvalidArgumentError) {
        assert(true)
      }
      else {
        assert(false)
      }
    }
  });

  it('Create and add non residential key', async function() {
    options.setProtocol(Protocol['U2F']);
    options.setHasResidentKey(false);

    await driver.addVirtualAuthenticator(options);

    let nonResidentCredential = new Credential().createNonResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      Buffer.from(base64EncodedPK, 'base64').toString('binary'),
      0);

    await driver.addCredential(nonResidentCredential);

    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
  });

  it('Get credential', async function() {
    options.setProtocol(Protocol['CTAP2']);
    options.setHasResidentKey(true);
    options.setHasUserVerification(true);
    options.setIsUserVerified(true);

    await driver.addVirtualAuthenticator(options);

    let residentCredential = new Credential().createResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      new Uint8Array([1]),
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(residentCredential);

    let credentialList = await driver.getCredentials();
    assert.equal(1, credentialList.length);

    let credential_id = credentialList[0].id();
    let test_id = new Uint8Array([1, 2, 3, 4]);

    assert(arraysEqual(credential_id, test_id));
    assert.equal(BASE64_ENCODED_PK, Buffer.from(credentialList[0].privateKey(), 'binary').toString('base64'));
  });

  it('Remove all credentials', async function() {
    await driver.addVirtualAuthenticator(options);

    let nonResidentCredential = new Credential().createNonResidentCredential(
      new Uint8Array([1, 2, 3, 4]),
      'localhost',
      Buffer.from(BASE64_ENCODED_PK, 'base64').toString('binary'),
      0);

    await driver.addCredential(nonResidentCredential);
    await driver.removeAllCredentials();

    let credentialList = await driver.getCredentials();
    assert.equal(0, credentialList.length);
  });

  it('Set is user verified', async function() {
    options.setIsUserVerified(true);
    assert.equal(options.getIsUserVerified(), true);
  });
});