I built a small “Account settings” page with four everyday components: a clickable div that saves the profile, a delete-account modal, an “Export as” menu button and a set of notification tabs. Then I broke their keyboard accessibility in thirteen ways that I see in real code reviews: outline: none, a positive tabindex, a dropdown hidden with opacity: 0, a keydown handler that swallows Tab, and so on.
axe-core 4.14, run with WCAG 2.2 AA and best-practice rules, flagged one of those thirteen. A Playwright suite that actually presses Tab, Shift+Tab, Enter, Space, arrow keys and Escape failed on all of them, 19 out of 19 tests.
That gap is the point of this article. Automated rule engines read the DOM; keyboard accessibility is about behavior over time: where focus goes after a key press, whether it can leave, whether you can see it. The axe-core README itself says axe finds “on average 57% of WCAG issues automatically”, and the WebAIM Million 2026 report reminds that “not all conformance failures can be automatically detected.”
If you already run an accessibility audit with axe on whole pages, this is the next layer: keyboard accessibility testing at the component level. We will:
- Write down the keyboard contract for each component from the WAI-ARIA Authoring Practices Guide (APG).
- Build the broken version and the fixed version of each component.
- Encode the contract as Playwright tests that check document.activeElement, :focus-visible and what is covering the focused element.
- Run axe-core against the broken page and compare.
Stack: @playwright/test 1.63.0 (Chromium 153), axe-core 4.14.0, @axe-core/playwright 4.14.0, plain HTML and JavaScript, no framework. All terminal output below is copied from real runs.
Keyboard accessibility in WCAG 2.2: five criteria
Keyboard navigation accessibility in WCAG 2.2 comes down to five success criteria, starting with WCAG 2.1.1 Keyboard. The wording below is quoted from the W3C Recommendation:
| Criterion | Level | What it requires | How we test it |
|---|---|---|---|
| 2.1.1 Keyboard | A | “All functionality of the content is operable through a keyboard interface” | Every action is reachable and fires on Enter/Space/arrows |
| 2.1.2 No Keyboard Trap | A | Focus “can be moved away from that component using only a keyboard interface” |
Tab and Shift+Tab can walk the whole page |
| 2.4.3 Focus Order | A | Components receive focus “in an order that preserves meaning and operability” | Recorded Tab sequence equals the visual order; modal keeps focus inside |
| 2.4.7 Focus Visible | AA | “the keyboard focus indicator is visible” | Focused element is visible and has an outline or box-shadow
|
| 2.4.11 Focus Not Obscured (Minimum) | AA | The focused component “is not entirely hidden due to author-created content” | Hit-test the focused element under a sticky banner |
2.4.11 is new in WCAG 2.2, which became a W3C Recommendation on 5 October 2023 (the current dated edition is from 12 December 2024). Its siblings 2.4.12 and 2.4.13 are AAA and out of scope here.
The keyboard accessibility WCAG criteria say nothing about arrow keys inside tabs, Escape in a menu, or where focus lands after a modal closes. Those conventions come from the ARIA Authoring Practices. The tests below encode them too.
The keyboard contract for each component
Before writing any code, I turn the APG patterns into a short contract per component. This is the spec the tests check.
Cheat sheet of the keyboard contract for button, modal dialog, menu button and tabs: which key does what, and where focus must land
The rules that cause the most bugs:
- Composite widgets are one Tab stop. APG’s keyboard interface guide says the tab sequence “should include only one focusable element of a composite UI component”. Inside a tablist or menu, arrow keys move focus, not Tab.
- A modal moves focus in and gives it back. On open, focus goes inside the dialog. On close, it returns to the element that opened it.
- Escape closes things. Dialogs, menus and popups.
- Focus is never lost. APG explicitly warns against focus falling back to body after a dialog closes or an item is deleted.
Step 1. Test helpers: where is focus, and can I see it?
Every keyboard test asks one of four questions. I put them in a fixture file so each spec stays readable. The variant option lets the same tests run against bad.html and good.html.
exports.test = base.test.extend({
variant: ['good', { option: true }],
page: async ({ page, variant }, use) => {
await page.goto('file://' + path.resolve(__dirname, `../site/${variant}.html`));
await use(page);
},
});
exports.expect = base.expect;
/** Short description of document.activeElement: "button#save", "body", ... */
exports.focused = page => page.evaluate(() => {
const el = document.activeElement;
return el ? el.tagName.toLowerCase() + (el.id ? '#' + el.id : '') : 'null';
});
/** Press Tab n times and record where focus lands after each press. */
exports.tabWalk = async (page, n, key = 'Tab') => {
const stops = [];
for (let i = 0; i < n; i++) {
await page.keyboard.press(key);
stops.push(await exports.focused(page));
}
return stops;
};
/** Is there any visible indicator on the focused element? outline or box-shadow. */
exports.focusIndicator = page => page.evaluate(() => {
const el = document.activeElement;
const s = getComputedStyle(el);
const outline = s.outlineStyle !== 'none' && parseFloat(s.outlineWidth) > 0;
const shadow = s.boxShadow !== 'none';
const visible = el.checkVisibility({ opacityProperty: true, visibilityProperty: true });
return { focusVisible: el.matches(':focus-visible'), indicator: outline || shadow, elementVisible: visible };
});
/** WCAG 2.4.11: is the focused element entirely covered by something else? */
exports.entirelyObscured = page => page.evaluate(() => {
const el = document.activeElement;
const r = el.getBoundingClientRect();
const pts = [[0.5, 0.5], [0.1, 0.1], [0.9, 0.1], [0.1, 0.9], [0.9, 0.9]]
.map(([fx, fy]) => [r.left + r.width * fx, r.top + r.height * fy]);
return pts.every(([x, y]) => {
const top = document.elementFromPoint(x, y);
return !top || !(el === top || el.contains(top));
});
});
Notes on the helpers:
- tabWalk uses Playwright’s keyboard API, which dispatches keydown and keyup, so the same key handlers run as for a real key press.
- focusIndicator checks two things separately. el.matches(':focus-visible') tells you the browser wants to show focus. Whether anything is actually drawn is a different question, so it also reads the computed outline and box-shadow, and calls checkVisibility({ opacityProperty: true }) to catch focusable elements that are invisible.
- entirelyObscured samples five points of the focused element with elementFromPoint. If every point hits something else, the element is treated as entirely hidden, a practical approximation of the 2.4.11 failure condition.
The project config runs the same spec twice:
// @ts-check
const { defineConfig } = require('@playwright/test');
module.exports = defineConfig({
testDir: './tests',
reporter: [['list']],
expect: { timeout: 2000 },
workers: 2,
use: { browserName: 'chromium', viewport: { width: 1000, height: 700 } },
projects: [
{ name: 'bad', testMatch: 'keyboard.spec.js', use: { variant: 'bad' } },
{ name: 'good', testMatch: 'keyboard.spec.js', use: { variant: 'good' } },
{ name: 'native', testMatch: 'native-dialog.spec.js' },
],
});
Step 2. Page-level checks: Tab order, traps, visible focus, obscured focus
These four tests cover 2.1.2, 2.4.3, 2.4.7 and 2.4.11 for the whole page.
test.describe('page-level keyboard checks', () => {
test('2.4.3 Tab order follows the visual order', async ({ page }) => {
expect(await tabWalk(page, 8)).toEqual([
'button#save', 'button#open-modal', 'button#menu-trigger', 'button#t-email',
'div#p-email', 'input#email', 'a#privacy', 'a#cookie-settings',
]);
});
test('2.1.2 Tab and Shift+Tab can leave every component', async ({ page }) => {
const forward = await tabWalk(page, 12);
expect(forward).toContain('a#cookie-settings'); // reached the last control
await page.locator('#cookie-settings').focus();
const back = await tabWalk(page, 12, 'Shift+Tab');
expect(back).toContain('button#save'); // and walked back to the first
});
test('2.4.7 every Tab stop has a visible focus indicator', async ({ page }) => {
const failures = [];
for (let i = 0; i < 8; i++) {
await page.keyboard.press('Tab');
const f = await focusIndicator(page);
if (!f.indicator || !f.elementVisible) failures.push({ el: await focused(page), ...f });
}
expect(failures).toEqual([]);
});
test('2.4.11 focused controls are not hidden behind the cookie bar', async ({ page }) => {
const hidden = [];
for (const id of ['#email', '#privacy']) {
await page.locator(id).focus(); // focus() scrolls it into view
if (await entirelyObscured(page)) hidden.push(id);
}
expect(hidden).toEqual([]);
});
});
Here is what the broken page did. The first test records where eight Tab presses land:
1) [bad] › page-level keyboard checks › 2.4.3 Tab order follows the visual order
Error: expect(received).toEqual(expected) // deep equality
- Expected - 7
+ Received + 7
Array [
- "button#save",
- "button#open-modal",
- "button#menu-trigger",
- "button#t-email",
- "div#p-email",
"input#email",
- "a#privacy",
- "a#cookie-settings",
+ "button#open-modal",
+ "a#csv",
+ "a#json",
+ "a#pdf",
+ "li",
+ "li",
+ "li",
]
Every line of that diff is a separate bug:
- input#email comes first because it has tabindex="1", although it sits in the footer. WebAIM’s advice is blunt: do not use tabindex values of 1 or greater.
- div#save and the “Export as” div never appear: they are not focusable at all.
- a#csv, a#json, a#pdf receive focus while the menu is closed. The dropdown was hidden with opacity: 0, which hides pixels, not focusability.
- li, li, li is the same element three times. Focus entered the first tab and never left.
Recorded Tab sequence on the fixed page versus the broken page: the broken page jumps to the footer, focuses three invisible menu links and then gets stuck on the first tab
That last one is a keyboard trap (2.1.2), and it came from code that looks harmless:
// "Make Enter work too" -- but preventDefault() runs for every key, Tab included
tab.addEventListener('keydown', e => {
e.preventDefault();
if (e.key === 'Enter') select(tab);
});
A mouse user never notices. A keyboard user is stuck on the first tab of the page with no way forward or back.
The focus-indicator test reported each stop. focusVisible: true with indicator: false is the signature of *:focus { outline: none; }: the browser decided to show focus and the CSS erased it.
3) [bad] › page-level keyboard checks › 2.4.7 every Tab stop has a visible focus indicator
Error: expect(received).toEqual(expected) // deep equality
- Expected - 1
+ Received + 50
- Array []
+ Array [
+ Object {
+ "el": "input#email",
+ "elementVisible": true,
+ "focusVisible": true,
+ "indicator": false,
+ },
+ Object {
+ "el": "button#open-modal",
+ "elementVisible": true,
+ "focusVisible": true,
+ "indicator": false,
+ },
+ Object {
+ "el": "a#csv",
+ "elementVisible": false,
+ "focusVisible": true,
+ "indicator": false,
+ },
... trimmed: a#json and a#pdf (elementVisible: false), then the same <li> three times
The fix for 2.4.7 is one rule. :focus-visible keeps the ring off for mouse clicks on buttons and on for keyboard users, which is usually why people removed the outline in the first place:
:focus-visible { outline: 3px solid #2563eb; outline-offset: 2px; }
For 2.4.11, the broken page has a fixed 120px cookie bar at the bottom. When the last controls on the page get focus, the browser scrolls as far as it can, and they end up under the bar:
4) [bad] › page-level keyboard checks › 2.4.11 focused controls are not hidden behind the cookie bar
Error: expect(received).toEqual(expected) // deep equality
- Expected - 1
+ Received + 4
- Array []
+ Array [
+ "#email",
+ "#privacy",
+ ]
The fix is to give the page room to scroll past the bar and tell the browser about it:
html { scroll-padding-bottom: 140px; }
body { padding-bottom: 120px; }
A detail I measured rather than assumed: in Chromium, focusing an element below the viewport scrolled it toward the middle of the screen, not to the bottom edge. So mid-page controls were never hidden; only the last controls on the page were. Removing scroll-padding-bottom alone did not bring the failure back, removing the body padding did. Keep both, but know which one is doing the work in your layout, and test the last focusable element on the page specifically.
Step 3. The div-button
The broken version:
<div class="btn" id="save" onclick="saved()">Save profile</div>
It looks and clicks like a button. It has no role, cannot receive focus, and ignores Enter and Space, so it fails 2.1.1 and exposes nothing useful to a screen reader.
The fix follows the first rule of ARIA use: if a native HTML element already has the semantics and behavior you need, use it.
<button type="button" class="btn" id="save">Save profile</button>
A native is focusable, gets a button role, and activates on both Enter and Space with no extra JavaScript. If you truly cannot change the element, the retrofit is role="button", tabindex="0" and key handlers for Enter and Space, and every piece of that is code you now own and must test.
The tests are the same for either approach:
test.describe('button', () => {
for (const key of ['Enter', 'Space']) {
test(`2.1.1 ${key} activates "Save profile"`, async ({ page }) => {
await page.locator('#save').focus();
await expect(page.locator('#save')).toBeFocused();
await page.keyboard.press(key);
await expect(page.locator('#status')).toHaveText('Saved');
});
}
});
On the broken page they fail before any key is pressed:
5) [bad] › button › 2.1.1 Enter activates "Save profile"
Error: expect(locator).toBeFocused() failed
Locator: locator('#save')
Expected: focused
Received: inactive
Timeout: 2000ms
Call log:
- Expect "toBeFocused" locator('#save') with timeout 2000ms
- waiting for locator('#save')
20 × locator resolved to <div id="save" class="btn" onclick="saved()">Save profile</div>
- unexpected value "inactive"
Step 4. An accessible modal: focus in, focus trapped, focus back
The broken modal is the most common one I see: a div overlay that appears on click. Focus stays on the trigger, Tab walks into the page behind the overlay, there is no Escape, and the close “x” is a div with an onclick. A keyboard user can open it and cannot close it.
The accessible modal per APG’s dialog pattern:
- role="dialog", aria-modal="true", aria-labelledby pointing at the visible title.
- On open, focus moves inside. APG suggests that for a destructive, hard-to-undo action you focus the least destructive button, so focus goes to Cancel, not Delete.
- Tab and Shift+Tab wrap inside the dialog.
- Escape closes it.
- On close, focus returns to the element that opened it.
const backdrop = $('#backdrop');
const dialog = $('#dialog');
const background = [$('#page'), $('#cookie')];
const FOCUSABLE = 'button:not([disabled]), [href], input:not([disabled]), select, textarea, [tabindex]:not([tabindex="-1"])';
let opener = null;
function openModal() {
opener = document.activeElement; // remember who opened it
backdrop.hidden = false;
background.forEach(el => { el.inert = true; }); // page behind: no focus, no clicks, no AT
$('#cancel').focus(); // least destructive action first
}
function closeModal() {
backdrop.hidden = true;
background.forEach(el => { el.inert = false; });
opener?.focus(); // focus goes back to "Delete account"
}
dialog.addEventListener('keydown', e => {
if (e.key === 'Escape') { e.preventDefault(); closeModal(); return; }
if (e.key !== 'Tab') return; // let every other key behave normally
const items = [...dialog.querySelectorAll(FOCUSABLE)];
const first = items[0], last = items.at(-1);
if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
});
$('#open-modal').addEventListener('click', openModal);
$('#cancel').addEventListener('click', closeModal);
$('#confirm').addEventListener('click', closeModal);
Two choices worth explaining:
- inert on the background. The inert attribute removes elements from the tab order, blocks clicks and hides them from assistive technologies. MDN marks it Baseline widely available since April 2023. It does the heavy lifting; the Tab handler only provides the wrap-around that APG describes.
- The Tab handler leaves every other key alone. Compare it with the tabs bug from Step 2. A focus trap that calls preventDefault() on everything is how you turn a modal into a 2.1.2 failure. A modal is allowed to contain focus because Escape and the buttons give the user a way out.
The tests:
test.describe('modal dialog', () => {
test.beforeEach(async ({ page }) => {
await page.locator('#open-modal').focus();
await page.keyboard.press('Enter');
});
test('opening moves focus into the dialog', async ({ page }) => {
expect(await insideDialog(page)).toBe(true);
});
test('2.4.3 Tab and Shift+Tab stay inside the dialog', async ({ page }) => {
for (const key of ['Tab', 'Shift+Tab']) {
for (let i = 0; i < 4; i++) {
await page.keyboard.press(key);
expect(await insideDialog(page), `${key} #${i + 1} -> ${await focused(page)}`).toBe(true);
}
}
});
test('Escape closes it and focus returns to the trigger', async ({ page }) => {
await page.keyboard.press('Escape');
await expect(page.locator('.modal')).toBeHidden();
await expect(page.locator('#open-modal')).toBeFocused();
});
});
On the broken page, the second test shows focus leaking straight to the page behind the overlay:
8) [bad] › modal dialog › 2.4.3 Tab and Shift+Tab stay inside the dialog
Error: Tab #1 -> a#csv
expect(received).toBe(expected) // Object.is equality
Expected: true
Received: false
What about the native <dialog> element?
showModal() makes the rest of the page inert and closes on Escape out of the box (MDN covers both). I tested what else it gives you in the same Chromium:
test('native <dialog>.showModal(): focus in, Escape out, focus restored', async ({ page }) => {
await page.goto('file://' + path.resolve(__dirname, '../site/native-dialog.html'));
await page.locator('#open-modal').focus();
await page.keyboard.press('Enter');
await expect(page.locator('#cancel')).toBeFocused(); // autofocus inside the dialog
const stops = await tabWalk(page, 4);
console.log('Tab x4 inside native dialog:', stops);
// no wrap: after the last button focus leaves the document ("body" here, browser UI in a real
// window) and then comes back to the dialog; the page behind is never reached
expect(stops).not.toContain('button#open-modal');
expect(stops).not.toContain('a#privacy');
await page.keyboard.press('Escape');
await expect(page.locator('#dialog')).toBeHidden();
await expect(page.locator('#open-modal')).toBeFocused(); // browser restored focus
});
Tab x4 inside native dialog: [ 'button#confirm', 'body', 'button#cancel', 'button#confirm' ]
✓ 1 [native] › native <dialog>.showModal(): focus in, Escape out, focus restored (1.0s)
Two observations from that run. Focus was restored to the “Delete account” button on Escape without a single line of my code. And Tab does not wrap: after the last button focus left the document (Playwright reports body; in a real window it is the browser UI) and then came back into the dialog. The page behind was never reachable, so this is not a 2.4.3 failure, but a test that asserts “every Tab stop is inside the dialog” will fail on a native dialog. Write the assertion as “never reaches the page behind” instead.
Step 5. Menu button: arrows, Escape, and no invisible tab stops
The broken menu has three problems. The trigger is a div, so it is not focusable. The menu opens on :hover. And the closed menu is hidden with opacity: 0; pointer-events: none, so its three links stay in the Tab sequence while invisible.
APG’s menu button pattern gives the contract: Enter, Space or Down Arrow open the menu and focus the first item; Up Arrow opens it and focuses the last item. Inside the menu, Up and Down move with optional wrap, Home and End jump, Escape closes and returns focus to the button, and Tab leaves the menu and closes it.
const trigger = $('#menu-trigger');
const menu = $('#export-menu');
const menuItems = [...menu.querySelectorAll('[role="menuitem"]')];
function openMenu(focusIndex = 0) {
menu.hidden = false;
trigger.setAttribute('aria-expanded', 'true');
menuItems.at(focusIndex).focus();
}
function closeMenu({ returnFocus = true } = {}) {
menu.hidden = true;
trigger.setAttribute('aria-expanded', 'false');
if (returnFocus) trigger.focus();
}
trigger.addEventListener('click', () => (menu.hidden ? openMenu(0) : closeMenu()));
trigger.addEventListener('keydown', e => {
if (e.key === 'ArrowDown') { e.preventDefault(); openMenu(0); }
if (e.key === 'ArrowUp') { e.preventDefault(); openMenu(-1); }
// Enter and Space already fire "click" on a native <button>
});
menu.addEventListener('keydown', e => {
const i = menuItems.indexOf(document.activeElement);
const n = menuItems.length;
const moves = { ArrowDown: (i + 1) % n, ArrowUp: (i - 1 + n) % n, Home: 0, End: n - 1 };
if (e.key in moves) { e.preventDefault(); menuItems[moves[e.key]].focus(); }
else if (e.key === 'Escape') { e.preventDefault(); closeMenu(); }
else if (e.key === 'Tab') { closeMenu({ returnFocus: false }); } // no preventDefault: Tab moves on
});
menuItems.forEach(item => item.addEventListener('click', () => {
$('#status').textContent = `Exporting ${item.textContent}`;
closeMenu();
}));
The markup uses aria-haspopup="menu", aria-expanded and aria-controls on a native button, and the closed list carries the hidden attribute. hidden takes the list out of rendering, and the “closed menu items are not in the Tab sequence” test confirms the items drop out of the Tab order; that alone fixes the invisible tab stops.
Each item gets tabindex="-1": focusable by script, never by Tab. The menu as a whole is one Tab stop, the trigger.
One judgment call: APG describes a menu as a widget that “offers a list of choices to the user, such as a set of actions or functions”. “Export as CSV / JSON / PDF” fits that. For a dropdown of site navigation links I prefer a plain disclosure button (aria-expanded on a button that shows a list of links), because role="menu" commits you to the full arrow-key contract above.
test.describe('menu button', () => {
test('closed menu items are not in the Tab sequence', async ({ page }) => {
const stops = await tabWalk(page, 10);
expect(stops.filter(s => /#(csv|json|pdf)$/.test(s))).toEqual([]);
});
for (const [key, first] of [['Enter', 'csv'], ['Space', 'csv'], ['ArrowDown', 'csv'], ['ArrowUp', 'pdf']]) {
test(`${key} opens the menu and focuses ${first.toUpperCase()}`, async ({ page }) => {
await page.locator('#menu-trigger').focus();
await expect(page.locator('#menu-trigger')).toBeFocused();
await page.keyboard.press(key);
await expect(page.locator('#menu-trigger')).toHaveAttribute('aria-expanded', 'true');
await expect(page.locator(`#${first}`)).toBeFocused();
});
}
test('arrows wrap, Escape closes and returns focus', async ({ page }) => {
await page.locator('#menu-trigger').focus();
await page.keyboard.press('Enter');
await page.keyboard.press('ArrowUp'); // wraps from first to last
await expect(page.locator('#pdf')).toBeFocused();
await page.keyboard.press('ArrowDown'); // and back to first
await expect(page.locator('#csv')).toBeFocused();
await page.keyboard.press('Escape');
await expect(page.locator('#menu-trigger')).toBeFocused();
await expect(page.locator('#menu-trigger')).toHaveAttribute('aria-expanded', 'false');
});
});
Step 6. Tabs with a roving tabindex
The broken tabs are <li tabindex="0"> elements: three Tab stops, no roles, no arrow keys, and the keyboard trap from Step 2.
The fixed version uses role="tablist", role="tab" with aria-selected and aria-controls, and role="tabpanel". The key part is the roving tabindex: exactly one tab has tabindex="0" (the selected one) and the rest have tabindex="-1". Arrow keys move focus and move the 0 along with it.
const tabs = [...document.querySelectorAll('[role="tab"]')];
function selectTab(tab) {
for (const t of tabs) {
const selected = t === tab;
t.setAttribute('aria-selected', String(selected));
t.tabIndex = selected ? 0 : -1; // roving tabindex: one tab stop for the whole tablist
document.getElementById(t.getAttribute('aria-controls')).hidden = !selected;
}
tab.focus();
}
$('#tabs').addEventListener('keydown', e => {
const i = tabs.indexOf(document.activeElement);
const n = tabs.length;
const moves = { ArrowRight: (i + 1) % n, ArrowLeft: (i - 1 + n) % n, Home: 0, End: n - 1 };
if (!(e.key in moves)) return; // Tab, Shift+Tab, Enter... untouched
e.preventDefault();
selectTab(tabs[moves[e.key]]); // automatic activation: panels are preloaded
});
tabs.forEach(t => t.addEventListener('click', () => selectTab(t)));
Panels get tabindex="0" because their content (one sentence) has nothing focusable inside; APG recommends that so the panel itself is reachable with Tab. Activation is automatic (the panel switches as focus moves) because the panels are already in the DOM; APG recommends manual activation only when showing a panel is slow.
Roving tabindex in a tablist: tabindex values before and after Right Arrow, and why Shift+Tab must land on the selected tab
test.describe('tabs', () => {
const tab = (page, n) => page.locator(`#tabs > :nth-child(${n})`);
test('the tablist is one Tab stop', async ({ page }) => {
await tab(page, 1).focus();
await page.keyboard.press('Tab');
expect(await focused(page)).toBe('div#p-email'); // straight to the panel
});
test('arrow keys move focus and selection, with wrap', async ({ page }) => {
await tab(page, 1).focus();
await page.keyboard.press('ArrowRight');
await expect(tab(page, 2)).toBeFocused();
await expect(tab(page, 2)).toHaveAttribute('aria-selected', 'true');
await expect(page.getByText('SMS notifications are off.')).toBeVisible();
await page.keyboard.press('ArrowLeft');
await page.keyboard.press('ArrowLeft'); // wraps to the last tab
await expect(tab(page, 3)).toBeFocused();
});
test('roving tabindex: Tab out and Shift+Tab back lands on the selected tab', async ({ page }) => {
await tab(page, 1).focus();
await page.keyboard.press('End'); // select "Push"
await page.keyboard.press('Tab'); // into the Push panel
await page.keyboard.press('Shift+Tab'); // back into the tablist
await expect(tab(page, 3)).toBeFocused();
});
test('Home and End jump to the first and last tab', async ({ page }) => {
await tab(page, 1).focus();
await page.keyboard.press('End');
await expect(tab(page, 3)).toBeFocused();
await page.keyboard.press('Home');
await expect(tab(page, 1)).toBeFocused();
});
});
The test I almost did not write
My first version of this suite had three tab tests: one Tab stop, arrows with wrap, Home/End. To check that the tests actually guard the code, I ran a few mutations on good.js. Deleting opener?.focus() in the modal failed the “focus returns to the trigger” test. Replacing :focus-visible with outline: none failed the 2.4.7 test. Deleting the roving line:
t.tabIndex = selected ? 0 : -1;
passed all 18 tests. The arrows still worked because they call focus() directly. What broke was re-entry: after selecting “Push” and tabbing into its panel, Shift+Tab went back to “Email”, the only tab that still had tabindex="0". APG says re-entry into tabs should land on the selected tab. The fourth tab test, “Tab out and Shift+Tab back lands on the selected tab”, exists because of that mutation, and it fails on the mutated code:
1) [good] › tabs › roving tabindex: Tab out and Shift+Tab back lands on the selected tab
Error: expect(locator).toBeFocused() failed
Locator: locator('#tabs > :nth-child(3)')
Expected: focused
Received: inactive
Timeout: 2000ms
Call log:
- Expect "toBeFocused" locator('#tabs > :nth-child(3)') with timeout 2000ms
- waiting for locator('#tabs > :nth-child(3)')
21 × locator resolved to <button role="tab" id="t-push" type="button" tabindex="-1" aria-selected="true" aria-controls="p-push">Push</button>
- unexpected value "inactive"
If you write keyboard tests for a roving tabindex, test leaving and re-entering, not only moving inside.
Step 7. What axe-core found on the broken page
First, the keyboard scoreboard. npm run test:bad runs the same 19 keyboard tests against the broken page:
✘ 1 [bad] › page-level keyboard checks › 2.4.3 Tab order follows the visual order (507ms)
✘ 2 [bad] › page-level keyboard checks › 2.1.2 Tab and Shift+Tab can leave every component (577ms)
✘ 3 [bad] › page-level keyboard checks › 2.4.7 every Tab stop has a visible focus indicator (584ms)
✘ 4 [bad] › page-level keyboard checks › 2.4.11 focused controls are not hidden behind the cookie bar (491ms)
✘ 5 [bad] › button › 2.1.1 Enter activates "Save profile" (2.4s)
✘ 6 [bad] › button › 2.1.1 Space activates "Save profile" (2.7s)
✘ 7 [bad] › modal dialog › opening moves focus into the dialog (506ms)
✘ 8 [bad] › modal dialog › 2.4.3 Tab and Shift+Tab stay inside the dialog (645ms)
✘ 9 [bad] › modal dialog › Escape closes it and focus returns to the trigger (2.8s)
✘ 10 [bad] › menu button › closed menu items are not in the Tab sequence (480ms)
✘ 11 [bad] › menu button › Enter opens the menu and focuses CSV (2.4s)
✘ 12 [bad] › menu button › Space opens the menu and focuses CSV (2.3s)
✘ 13 [bad] › menu button › ArrowDown opens the menu and focuses CSV (2.6s)
✘ 14 [bad] › menu button › ArrowUp opens the menu and focuses PDF (2.5s)
✘ 15 [bad] › menu button › arrows wrap, Escape closes and returns focus (2.4s)
✘ 16 [bad] › tabs › the tablist is one Tab stop (398ms)
✘ 17 [bad] › tabs › arrow keys move focus and selection, with wrap (2.8s)
✘ 18 [bad] › tabs › roving tabindex: Tab out and Shift+Tab back lands on the selected tab (2.4s)
✘ 19 [bad] › tabs › Home and End jump to the first and last tab (2.4s)
19 failed
npm run test:good passes all of them plus the native dialog test, 20 out of 20. Now the comparison. The axe script runs every WCAG 2.0/2.1/2.2 A and AA rule plus best practices, and additionally enables focus-order-semantics, which is experimental and off by default. It scans each page twice: as loaded and with the modal open.
const states = {
'page loaded': async () => {},
'modal open': async page => { await page.locator('#open-modal').click(); },
};
(async () => {
const browser = await chromium.launch();
for (const variant of ['bad', 'good']) {
for (const [state, setup] of Object.entries(states)) {
const context = await browser.newContext(); // AxeBuilder refuses browser.newPage()
const page = await context.newPage();
await page.goto('file://' + path.resolve(__dirname, `site/${variant}.html`));
await setup(page);
const { violations } = await new AxeBuilder({ page })
.withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa', 'best-practice'])
.options({ rules: { 'focus-order-semantics': { enabled: true } } }) // experimental, off by default
.analyze();
console.log(`${variant.padEnd(4)} | ${state.padEnd(11)} | ${violations.length} violation(s)`);
for (const v of violations) {
const targets = v.nodes.map(n => n.target.join(' ')).join(', ');
console.log(` - ${v.id} (${v.impact}): ${targets}`);
}
await context.close();
}
}
await browser.close();
})();
One gotcha from the first run: @axe-core/playwright threw Please use browser.newContext() when the page came from browser.newPage(). Create a context first.
bad | page loaded | 2 violation(s)
- region (moderate): .cookie
- tabindex (serious): #email
bad | modal open | 2 violation(s)
- region (moderate): .x, .modal > h2, p, .cookie
- tabindex (serious): #email
good | page loaded | 0 violation(s)
good | modal open | 0 violation(s)
On the broken page axe reported two rules. tabindex (best-practice) caught the positive tabindex="1", the root cause of one of the thirteen keyboard bugs. region complained that the cookie bar and the modal content are outside landmarks, which is a real issue but not a keyboard one. The fixed page is clean.
Thirteen keyboard defects on the test page with their WCAG criterion, whether the Playwright keyboard tests caught them and whether axe-core 4.14 did
This is not a flaw in axe; it is what a static rule can see. The axe-core rule list has no rule for a missing focus indicator or a keyboard trap. A div with an onclick looks like any other div, because listeners are not in the DOM. Focus moving into a modal or coming back after close only exists after a key press. Keep axe for what it does well and add behavior tests for the rest.
Gotchas I hit or nearly shipped
- preventDefault() at the top of a keydown handler. The shortest path to a keyboard trap. Handle the keys you own and return early for the rest.
- :focus-visible is not proof of a visible ring. It is a browser heuristic. Assert on computed styles as well.
- Focus to body after close. If the opener can be removed (a “Delete row” button that deletes its own row), pick a sensible fallback target; APG’s dialog pattern describes this case.
- Native does not wrap Tab. Adjust the assertion, not the dialog.
- A CSS display value beats hidden. MDN notes that setting display on a hidden element overrides the hidden state. My backdrop uses display: grid, so it needs .backdrop[hidden] { display: none; } or the “closed” modal stays on screen.
- Clicking instead of pressing. A test that calls .click() to open a modal proves nothing about the keyboard.
A keyboard accessibility checklist for every component PR
- Every action works with Tab plus Enter or Space (2.1.1).
- Tab and Shift+Tab can enter and leave every component (2.1.2).
- Tab order matches the visual order; no positive tabindex (2.4.3).
- Every Tab stop is visible and has an indicator (2.4.7).
- Sticky headers, footers and banners never fully cover the focused control (2.4.11).
- Composite widgets are one Tab stop; arrows move inside; re-entry lands on the selected item.
- Modals: focus in, contained, Escape closes, focus returns. Menus: Escape closes and returns focus; closed items are not focusable.
- Run axe too, for the positive tabindex and the many non-keyboard issues.
Wrapping up
None of the thirteen bugs is exotic; each is a line of CSS, a missing attribute or one preventDefault(). They survive code review because they are invisible to the mouse and to static scanners. Written as Playwright tests, the APG contract turned each one into a red line with an exact element name.
The full project (two HTML pages, the components, 20 tests and the axe script) runs with npm run test:good, npm run test:bad and npm run axe.
What is the keyboard bug you keep finding in reviews? I would like to know which ones I should add to the suite.




Top comments (2)
The contract‑first approach you showed for each widget is spot‑on; encoding the ARIA Authoring Practices into Playwright tests makes the focus flow explicit and catches the subtle traps that axe‑core skips. One nuance that often shows up in real‑world code is that focus‑visible styles can be overridden by a parent’s
overflow: hiddenor a transformed container, so the element may technically have focus but be clipped out of view. Adding a small visual‑regression check that asserts the bounding rect ofdocument.activeElementstays within the viewport can surface that edge case without extra manual testing.One edge case for the focusIndicator helper: outline: 2px solid transparent is a common pattern (it keeps a ring in Windows forced-colors mode while a box-shadow does the visible work), but if someone later drops the box-shadow and keeps the transparent outline, the helper still reports indicator: true. Checking that the computed outlineColor isn't fully transparent would close that gap. The reverse can happen too: a focus style that only changes background-color or border gets flagged as missing even though it's visible.