Ensure keyboard focus is never trapped on an element without an obvious way to move focus out of the element. Make sure the user can move focus to and from all focusable elements using a keyboard only.
Language: Java
Framework: Selenium 4
1//Assumptions:2//1. The application's UI elements are all given valid focus state attributes3//2. The WebDriver connection, remote or local, uses the DesiredCapabilities object to set certain properties4//3. The Accessibility method to test keyboard focus works on both local and remote WebDriver instances56//We'll start by importing the necessary Selenium libraries/packages for Java.7import org.openqa.selenium.By;8import org.openqa.selenium.WebDriver;9import org.openqa.selenium.WebElement;10import org.openqa.selenium.chrome.ChromeDriver;11import org.openqa.selenium.remote.DesiredCapabilities;12import org.openqa.selenium.remote.RemoteWebDriver;1314import java.net.URL;1516public class TestAccessibility {1718 public static void main(String[] args) {19 20 //Set desired capabilities for connecting to remote client21 DesiredCapabilities capabilities = DesiredCapabilities.chrome();22 capabilities.setCapability("platform", "LINUX");23 capabilities.setCapability("version", "66.0");2425 //Initialize WebDriver26 WebDriver driver = null;27 try {28 //Specify IP address of the RemoteWebDriver server29 URL url = new URL("http://10.0.0.1:4444/wd/hub"); //example URL, replace with your own30 //Initialize remote WebDriver with desired capabilities31 driver = new RemoteWebDriver(url, capabilities);32 } catch (Exception e) {33 e.printStackTrace();34 }3536 //Assuming the website we're testing is already open on the web browser, let's check for keyboard accessibility37 //First, we'll find all the focusable elements on the page using the tabindex attribute38 //We'll use a CSS selector to identify the elements. Assuming tabindex="0" is used for all focusable elements39 //This selector will find all elements with tabindex greater than -1 and then apply a filter to get the visible elements40 WebElement[] elements = driver.findElements(By.cssSelector("*[tabindex]:not([tabindex='-1']):visible"));4142 //Now that we have the elements, we can iterate through them and check if the keyboard focus is trapped.43 for (WebElement element: elements) {44 //First, we'll click on the element to give it focus45 element.click();46 //Then, we'll check if the focus is still on the same element by comparing its link text to the47 //activeElement property of the WebDriver instance. If the active element is different from the48 //clicked element, we can assume the focus has moved to another focusable element.49 if (!driver.switchTo().activeElement().getText().equals(element.getText())) {50 //If the focus has moved to another focusable element, we'll continue to the next element51 continue;52 }53 //If the focus is still on the same element, we'll check if there is an obvious way to move focus out of it.54 //We'll check if the element has a valid 'role' attribute, which will indicate that it is a widget (button, link, etc.)55 //and not a container (e.g., div) that requires further navigation.56 if (element.getAttribute("role") != null) {57 //If the element has a valid role attribute - such as "button", "link", "textbox" or "checkbox" - it is a widget that58 //can be easily navigated. We'll move the focus to the next focusable element and repeat the process.59 element.sendKeys("\t");60 } else {61 //If the element does not have a valid role attribute, we'll assume it is a container and will require62 //further navigation. We'll simulate a 'down arrow' keypress to move focus to the first focusable element63 //within the container, and repeat the process until we find a valid widget with a role attribute.64 element.sendKeys("\uE015"); //down arrow key65 while (element.getAttribute("role") == null) {66 Thread.sleep(1000); //wait for 1 second to avoid overloading the browser67 element.sendKeys("\uE015"); //repeat down keypress until a valid widget is found68 }69 //Once we find a valid widget, we'll move focus to it and repeat the process.70 element.sendKeys("\t");71 }72 }73 }74}
Language: Python
Framework: Selenium 4
1Assumptions:2- The web application being tested has only one page with several focusable elements3- All focusable elements are visible and enabled4- The web application is accessible through a local URL5- The keyboard input is working properly on the testing machine67Code:89# Import required Selenium modules10from selenium import webdriver11from selenium.webdriver.common.keys import Keys1213# Create a new instance of Firefox web driver14driver = webdriver.Firefox()1516# Navigate to the web application's page17driver.get("http://localhost:8080/myapp/index.html")1819# Find all focusable elements on the page20focusable_elements = driver.find_elements_by_xpath(21 "//*[@tabindex][not(@disabled)]"22)2324# Test that each focusable element is working properly25for element in focusable_elements:26 # Click on the element to give it keyboard focus27 element.click()28 29 # Check that the element has keyboard focus30 is_focused = driver.switch_to.active_element == element31 32 # Check that the element has an obvious way to move focus out of it33 if element.tag_name.lower() == "a":34 has_obvious_way_out = True35 elif element.tag_name.lower() in ["input", "textarea"]:36 has_obvious_way_out = element.is_displayed() and element.is_enabled()37 else:38 has_obvious_way_out = False39 40 assert is_focused and has_obvious_way_out, \41 "Element '{}' does not meet accessibility requirements".format(element.get_attribute("id"))4243# Close the web driver44driver.quit()4546# Commented code to connect to remote client with desired capabilities47"""48from selenium import webdriver49from selenium.webdriver.common.keys import Keys50from selenium.webdriver.common.desired_capabilities import DesiredCapabilities5152# Set the desired capabilities for the remote client53capabilities = DesiredCapabilities.CHROME54capabilities['version'] = 'latest'55capabilities['platform'] = 'Windows 10'5657# Create a new instance of the remote web driver58driver = webdriver.Remote(59 command_executor='http://localhost:4444/wd/hub',60 desired_capabilities=capabilities61)6263# Rest of the code is the same as above64"""
Disclaimer: Following code snippets and related information have been sourced from GitHub and/or generated using AI code generation tools. LambdaTest takes no responsibility in the accuracy of the code and is not liable for any damages.
Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.
Test Intelligently and ship faster. Deliver unparalleled digital experiences for real world enterprises.
Start Free Testing