Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

fix(a11y): treat inert elements and content outside of modal dialogs as hidden (#43211)

Dmitry Gozman7d587a2e85b1
diff --git a/docs/src/actionability.md b/docs/src/actionability.md
index 3510171e5c..485b474c2a 100644
--- a/docs/src/actionability.md
+++ b/docs/src/actionability.md
@@ -14,31 +14,32 @@ For example, for [`method: Locator.click`], Playwright will ensure that:
- element is [Stable], as in not animating or completed animation
- element [Receives Events], as in not obscured by other elements
- element is [Enabled]
+- element is [Not Inert]
Here is the complete list of actionability checks performed for each action:
-| Action | [Visible] | [Stable] | [Receives Events] | [Enabled] | [Editable] |
-| :- | :-: | :-: | :-: | :-: | :-: |
-| [`method: Locator.check`] | Yes | Yes | Yes | Yes | - |
-| [`method: Locator.click`] | Yes | Yes | Yes | Yes | - |
-| [`method: Locator.dblclick`] | Yes | Yes | Yes | Yes | - |
-| [`method: Locator.setChecked`] | Yes | Yes | Yes | Yes | - |
-| [`method: Locator.tap`] | Yes | Yes | Yes | Yes | - |
-| [`method: Locator.uncheck`] | Yes | Yes | Yes | Yes | - |
-| [`method: Locator.hover`] | Yes | Yes | Yes | - | - |
-| [`method: Locator.dragTo`] | Yes | Yes | Yes | - | - |
-| [`method: Locator.screenshot`] | Yes | Yes | - | - | - |
-| [`method: Locator.fill`] | Yes | - | - | Yes | Yes |
-| [`method: Locator.clear`] | Yes | - | - | Yes | Yes |
-| [`method: Locator.selectOption`] | Yes | - | - | Yes | - |
-| [`method: Locator.selectText`] | Yes | - | - | - | - |
-| [`method: Locator.scrollIntoViewIfNeeded`] | - | Yes | - | - | - |
-| [`method: Locator.blur`] | - | - | - | - | - |
-| [`method: Locator.dispatchEvent`] | - | - | - | - | - |
-| [`method: Locator.focus`] | - | - | - | - | - |
-| [`method: Locator.press`] | - | - | - | - | - |
-| [`method: Locator.pressSequentially`] | - | - | - | - | - |
-| [`method: Locator.setInputFiles`] | - | - | - | - | - |
+| Action | [Visible] | [Stable] | [Receives Events] | [Enabled] | [Editable] | [Not Inert] |
+| :- | :-: | :-: | :-: | :-: | :-: | :-: |
+| [`method: Locator.check`] | Yes | Yes | Yes | Yes | - | Yes |
+| [`method: Locator.click`] | Yes | Yes | Yes | Yes | - | Yes |
+| [`method: Locator.dblclick`] | Yes | Yes | Yes | Yes | - | Yes |
+| [`method: Locator.setChecked`] | Yes | Yes | Yes | Yes | - | Yes |
+| [`method: Locator.tap`] | Yes | Yes | Yes | Yes | - | Yes |
+| [`method: Locator.uncheck`] | Yes | Yes | Yes | Yes | - | Yes |
+| [`method: Locator.hover`] | Yes | Yes | Yes | - | - | - |
+| [`method: Locator.dragTo`] | Yes | Yes | Yes | - | - | - |
+| [`method: Locator.screenshot`] | Yes | Yes | - | - | - | - |
+| [`method: Locator.fill`] | Yes | - | - | Yes | Yes | Yes |
+| [`method: Locator.clear`] | Yes | - | - | Yes | Yes | Yes |
+| [`method: Locator.selectOption`] | Yes | - | - | Yes | - | - |
+| [`method: Locator.selectText`] | Yes | - | - | - | - | - |
+| [`method: Locator.scrollIntoViewIfNeeded`] | - | Yes | - | - | - | - |
+| [`method: Locator.blur`] | - | - | - | - | - | - |
+| [`method: Locator.dispatchEvent`] | - | - | - | - | - | - |
+| [`method: Locator.focus`] | - | - | - | - | - | - |
+| [`method: Locator.press`] | - | - | - | - | - | - |
+| [`method: Locator.pressSequentially`] | - | - | - | - | - | - |
+| [`method: Locator.setInputFiles`] | - | - | - | - | - | - |
## Forcing actions
@@ -108,6 +109,14 @@ Element is **readonly** when:
- it is a `<select>`, `<input>` or `<textarea>` with a `[readonly]` attribute;
- it has an `[aria-readonly=true]` attribute and an aria role that [supports it](https://w3c.github.io/aria/#aria-readonly).
+## Not Inert
+
+Element is considered not inert when it is **not** a part of an inert subtree. Inert elements cannot be focused, clicked or otherwise interacted with, and are excluded from the accessibility tree.
+
+Element is **inert** when:
+- it is an element with the [`inert`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/inert) attribute, or a descendant of such an element;
+- a modal `<dialog>` is open, and the element is not a part of that dialog.
+
## Receives Events
Element is considered receiving pointer events when it is the hit target of the pointer event at the action point. For example, when clicking at the point `(10;10)`, Playwright checks whether some other element (usually an overlay) will instead capture the click at `(10;10)`.
@@ -122,3 +131,4 @@ For example, consider a scenario where Playwright will click `Sign Up` button re
[Enabled]: #enabled "Enabled"
[Editable]: #editable "Editable"
[Receives Events]: #receives-events "Receives Events"
+[Not Inert]: #not-inert "Not Inert"
diff --git a/packages/injected/src/ariaSnapshot.ts b/packages/injected/src/ariaSnapshot.ts
index 61f96fe040..e68ae44b40 100644
--- a/packages/injected/src/ariaSnapshot.ts
+++ b/packages/injected/src/ariaSnapshot.ts
@@ -124,8 +124,9 @@ export function generateAriaTree(rootElement: Element, publicOptions: AriaTreeOp
visible = isElementVisibleForAria && isElementVisible(element);
// Optimization: if we only consider aria visibility, we can skip child elements because
- // they will not be visible for aria as well.
- if (options.visibility === 'aria' && !visible)
+ // they will not be visible for aria as well. The only exception is the topmost modal dialog
+ // that escapes inertness of its ancestors.
+ if (options.visibility === 'aria' && !visible && !roleUtils.containsTopmostModalDialog(element))
return;
const ariaChildren: Element[] = [];
diff --git a/packages/injected/src/domUtils.ts b/packages/injected/src/domUtils.ts
index 4b6d1dbf9a..17a1668649 100644
--- a/packages/injected/src/domUtils.ts
+++ b/packages/injected/src/domUtils.ts
@@ -16,11 +16,16 @@
type GlobalOptions = {
browserNameForWorkarounds?: string;
+ skipInertCheck?: boolean;
+ skipDialogCheck?: boolean;
};
let globalOptions: GlobalOptions = {};
export function setGlobalOptions(options: GlobalOptions) {
globalOptions = options;
}
+export function getGlobalOptions(): GlobalOptions {
+ return globalOptions;
+}
export function isInsideScope(scope: Node, element: Element | undefined): boolean {
while (element) {
diff --git a/packages/injected/src/injectedScript.ts b/packages/injected/src/injectedScript.ts
index 64043ea4f1..5346db99f5 100644
--- a/packages/injected/src/injectedScript.ts
+++ b/packages/injected/src/injectedScript.ts
@@ -26,7 +26,7 @@ import { beginDOMCaches, enclosingShadowRootOrDocument, endDOMCaches, isElementV
import { Highlight } from './highlight';
import { kLayoutSelectorNames, layoutSelectorScore } from './layoutSelectorUtils';
import { createRoleEngine } from './roleSelectorEngine';
-import { beginAriaCaches, endAriaCaches, getAriaDisabled, getAriaRole, getCheckedAllowMixed, getCheckedWithoutMixed, getElementAccessibleDescription, getElementAccessibleErrorMessage, getElementAccessibleNameText, getReadonly } from './roleUtils';
+import { beginAriaCaches, endAriaCaches, getAriaDisabled, getAriaRole, getCheckedAllowMixed, getCheckedWithoutMixed, getElementAccessibleDescription, getElementAccessibleErrorMessage, getElementAccessibleNameText, getReadonly, isElementInert } from './roleUtils';
import { SelectorEvaluatorImpl, sortInDOMOrder } from './selectorEvaluator';
import { generateSelector } from './selectorGenerator';
import { elementMatchesText, elementText, getElementLabels } from './selectorUtils';
@@ -59,7 +59,7 @@ export type FrameExpectParams = {
isNot: boolean,
};
-export type ElementState = 'visible' | 'hidden' | 'enabled' | 'disabled' | 'editable' | 'checked' | 'unchecked' | 'indeterminate' | 'stable';
+export type ElementState = 'visible' | 'hidden' | 'enabled' | 'disabled' | 'editable' | 'checked' | 'unchecked' | 'indeterminate' | 'stable' | 'non-inert';
export type ElementStateWithoutStable = Exclude<ElementState, 'stable'>;
export type ElementStateQueryResult = { matches: boolean, received?: string | 'error:notconnected', isRadio?: boolean };
export type ExpectReceived = { value?: any, ariaSnapshot?: string };
@@ -87,6 +87,8 @@ export type InjectedScriptOptions = {
shouldPrependErrorPrefix?: boolean;
isUtilityWorld?: boolean;
customEngines: { name: string, source: string }[];
+ skipInertCheck?: boolean;
+ skipDialogCheck?: boolean;
};
export class InjectedScript {
@@ -252,7 +254,11 @@ export class InjectedScript {
this._browserName = options.browserName;
this._shouldPrependErrorPrefix = !!options.shouldPrependErrorPrefix;
this._isUtilityWorld = !!options.isUtilityWorld;
- setGlobalOptions({ browserNameForWorkarounds: options.browserName });
+ setGlobalOptions({
+ browserNameForWorkarounds: options.browserName,
+ skipInertCheck: options.skipInertCheck,
+ skipDialogCheck: options.skipDialogCheck,
+ });
this._setupGlobalListenersRemovalDetection();
this._setupHitTargetInterceptors();
@@ -804,6 +810,14 @@ export class InjectedScript {
};
}
+ if (state === 'non-inert') {
+ const inert = isElementInert(element);
+ return {
+ matches: !inert,
+ received: inert ? 'inert' : 'non-inert'
+ };
+ }
+
if (state === 'editable') {
const disabled = getAriaDisabled(element);
const readonly = getReadonly(element);
diff --git a/packages/injected/src/roleUtils.ts b/packages/injected/src/roleUtils.ts
index d0e2359812..6f8f295a81 100644
--- a/packages/injected/src/roleUtils.ts
+++ b/packages/injected/src/roleUtils.ts
@@ -16,7 +16,7 @@
import * as css from '@isomorphic/cssTokenizer';
-import { beginDOMCaches, closestCrossShadow, elementSafeTagName, enclosingShadowRootOrDocument, endDOMCaches, getElementComputedStyle, isElementStyleVisibilityVisible, isListBoxSelect, isVisibleTextNode, parentElementOrShadowHost } from './domUtils';
+import { beginDOMCaches, closestCrossShadow, elementSafeTagName, enclosingShadowRootOrDocument, endDOMCaches, getElementComputedStyle, getGlobalOptions, isElementStyleVisibilityVisible, isListBoxSelect, isVisibleTextNode, parentElementOrShadowHost } from './domUtils';
import type { AriaRole } from '@isomorphic/ariaSnapshot';
@@ -331,7 +331,68 @@ export function isElementHiddenForAria(element: Element): boolean {
const isOptionInsideSelect = element.nodeName === 'OPTION' && !!element.closest('select');
if (!isOptionInsideSelect && !isSlot && !isElementStyleVisibilityVisible(element, style))
return true;
- return belongsToDisplayNoneOrAriaHiddenOrNonSlotted(element);
+ return belongsToDisplayNoneOrAriaHiddenOrNonSlotted(element) || isElementInert(element);
+}
+
+// https://html.spec.whatwg.org/multipage/interaction.html#inert-subtrees
+// Inert elements cannot be focused, clicked or otherwise interacted with,
+// and are excluded from the accessibility tree.
+export function isElementInert(element: Element): boolean {
+ if (getGlobalOptions().skipInertCheck)
+ return false;
+ let inert = cacheIsInert?.get(element);
+ if (inert === undefined) {
+ if (element.hasAttribute('inert')) {
+ inert = true;
+ } else if (element === topmostModalDialog(element.ownerDocument)?.dialog) {
+ // The topmost modal dialog escapes inertness of its ancestors.
+ inert = false;
+ } else {
+ // Inert applies to all flat tree descendants, so we look up the hierarchy.
+ const parent = parentElementOrShadowHost(element);
+ if (parent) {
+ inert = isElementInert(parent);
+ } else {
+ // While a modal dialog is open, everything in the document, except for the dialog
+ // itself and its descendants, is inert.
+ inert = element.isConnected && !!topmostModalDialog(element.ownerDocument);
+ }
+ }
+ cacheIsInert?.set(element, inert);
+ }
+ return inert;
+}
+
+// Returns true for ancestors of the topmost modal dialog. Such ancestors are inert,
+// but still contain the non-inert dialog in their subtree.
+export function containsTopmostModalDialog(element: Element): boolean {
+ return !!topmostModalDialog(element.ownerDocument)?.ancestors.has(element);
+}
+
+function topmostModalDialog(document: Document): ModalDialogInfo | undefined {
+ if (getGlobalOptions().skipInertCheck || getGlobalOptions().skipDialogCheck)
+ return;
+ let info = cacheModalDialog?.get(document);
+ if (info === undefined) {
+ info = null;
+ try {
+ // There is no way to determine the top layer order, so we assume that the last modal
+ // dialog in the document order is the topmost one. Note that this does not pierce
+ // shadow roots.
+ const dialogs = document.querySelectorAll('dialog:modal');
+ if (dialogs.length) {
+ const dialog = dialogs[dialogs.length - 1];
+ const ancestors = new Set<Element>();
+ for (let e = parentElementOrShadowHost(dialog); e; e = parentElementOrShadowHost(e))
+ ancestors.add(e);
+ info = { dialog, ancestors };
+ }
+ } catch {
+ // Older browsers might not support the :modal pseudo-class.
+ }
+ cacheModalDialog?.set(document, info);
+ }
+ return info || undefined;
}
function belongsToDisplayNoneOrAriaHiddenOrNonSlotted(element: Element): boolean {
@@ -1257,6 +1318,8 @@ function getAccessibleNameFromAssociatedLabels(labels: Iterable<HTMLLabelElement
}
export function receivesPointerEvents(element: Element): boolean {
+ if (isElementInert(element))
+ return false;
const cache = cachePointerEvents!;
let e: Element | undefined = element;
let result: boolean | undefined;
@@ -1298,6 +1361,9 @@ let cacheAccessibleDescription: Map<Element, AccessibleDescription> | undefined;
let cacheAccessibleDescriptionHidden: Map<Element, AccessibleDescription> | undefined;
let cacheAccessibleErrorMessage: Map<Element, string> | undefined;
let cacheIsHidden: Map<Element, boolean> | undefined;
+let cacheIsInert: Map<Element, boolean> | undefined;
+type ModalDialogInfo = { dialog: Element, ancestors: Set<Element> };
+let cacheModalDialog: Map<Document, ModalDialogInfo | null> | undefined;
let cachePseudoContent: Map<Element, string | undefined> | undefined;
let cachePseudoContentBefore: Map<Element, string | undefined> | undefined;
let cachePseudoContentAfter: Map<Element, string | undefined> | undefined;
@@ -1319,6 +1385,8 @@ export function beginAriaCaches() {
cacheAccessibleDescriptionHidden ??= new Map();
cacheAccessibleErrorMessage ??= new Map();
cacheIsHidden ??= new Map();
+ cacheIsInert ??= new Map();
+ cacheModalDialog ??= new Map();
cachePseudoContent ??= new Map();
cachePseudoContentBefore ??= new Map();
cachePseudoContentAfter ??= new Map();
@@ -1335,6 +1403,8 @@ export function endAriaCaches() {
cacheAccessibleDescriptionHidden = undefined;
cacheAccessibleErrorMessage = undefined;
cacheIsHidden = undefined;
+ cacheIsInert = undefined;
+ cacheModalDialog = undefined;
cachePseudoContent = undefined;
cachePseudoContentBefore = undefined;
cachePseudoContentAfter = undefined;
diff --git a/packages/playwright-core/src/server/dom.ts b/packages/playwright-core/src/server/dom.ts
index 2f1e43834b..0b9ba79460 100644
--- a/packages/playwright-core/src/server/dom.ts
+++ b/packages/playwright-core/src/server/dom.ts
@@ -109,6 +109,8 @@ export class FrameExecutionContext extends js.ExecutionContext {
shouldPrependErrorPrefix: this.delegate.shouldPrependErrorPrefix(),
isUtilityWorld: this.world === 'utility',
customEngines,
+ skipInertCheck: !!process.env.PLAYWRIGHT_SKIP_INERT_CHECK,
+ skipDialogCheck: !!process.env.PLAYWRIGHT_SKIP_DIALOG_CHECK,
};
const globalsSnapshot = this.frame._page.delegate.noUtilityWorld?.() ? js.mainWorldGlobalsSnapshotSource : '';
const source = `
@@ -370,7 +372,10 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
continue;
}
if (typeof result === 'object' && 'missingState' in result) {
- progress.log(` element is not ${result.missingState}`);
+ if (result.missingState === 'non-inert')
+ progress.log(' element is inert');
+ else
+ progress.log(` element is not ${result.missingState}`);
continue;
}
return result;
@@ -427,7 +432,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
await progress.race((options as any).__testHookBeforeStable());
if (!force) {
- const elementStates: ElementState[] = action.waitForEnabled ? ['visible', 'enabled', 'stable'] : ['visible', 'stable'];
+ const elementStates: ElementState[] = action.waitForEnabled ? ['visible', 'enabled', 'stable', 'non-inert'] : ['visible', 'stable'];
progress.log(` waiting for element to be ${action.waitForEnabled ? 'visible, enabled and stable' : 'visible and stable'}`);
const result = await progress.race(this.evaluateInUtility(async ([injected, node, { elementStates, frameVisible }]) => {
return await injected.checkElementStates(node, elementStates, frameVisible);
@@ -631,7 +636,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
progress.log(' waiting for element to be visible, enabled and editable');
const result = await progress.race(this.evaluateInUtility(async ([injected, node, { value, force, frameVisible }]) => {
if (!force) {
- const checkResult = await injected.checkElementStates(node, ['visible', 'enabled', 'editable'], frameVisible);
+ const checkResult = await injected.checkElementStates(node, ['visible', 'enabled', 'editable', 'non-inert'], frameVisible);
if (checkResult)
return checkResult;
}
diff --git a/tests/page/page-aria-snapshot-ai.spec.ts b/tests/page/page-aria-snapshot-ai.spec.ts
index 867f088ba6..3068921df8 100644
--- a/tests/page/page-aria-snapshot-ai.spec.ts
+++ b/tests/page/page-aria-snapshot-ai.spec.ts
@@ -986,3 +986,42 @@ it('should not include hidden iframes', async ({ page }) => {
expect(snapshot).not.toContain('Hidden');
expect(snapshot).not.toContain('None');
});
+
+it('should not generate refs for inert elements', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/36938' } }, async ({ page }) => {
+ await page.setContent(`
+ <button>with-ref</button>
+ <button inert>no-ref</button>
+ <div inert>
+ <button>no-ref</button>
+ </div>
+ `);
+
+ const snapshot = await snapshotForAI(page);
+ expect(snapshot).toContainYaml(`
+ - generic [active] [ref=e1]:
+ - button "with-ref" [ref=e2]
+ - button: no-ref
+ - generic:
+ - button: no-ref
+ `);
+});
+
+it('should not generate refs for elements outside of a modal dialog', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/36938' } }, async ({ page }) => {
+ await page.setContent(`
+ <button>Outside</button>
+ <dialog id=dialog>
+ <button>Inside</button>
+ </dialog>
+ <script>
+ document.getElementById('dialog').showModal();
+ </script>
+ `);
+
+ const snapshot = await snapshotForAI(page);
+ expect(snapshot).toContainYaml(`
+ - generic:
+ - button: Outside
+ - dialog [ref=e1]:
+ - button "Inside" [active] [ref=e2]
+ `);
+});
diff --git a/tests/page/page-aria-snapshot.spec.ts b/tests/page/page-aria-snapshot.spec.ts
index 2644300a16..13b808bc39 100644
--- a/tests/page/page-aria-snapshot.spec.ts
+++ b/tests/page/page-aria-snapshot.spec.ts
@@ -861,3 +861,49 @@ it('should not include hidden iframes', async ({ page }) => {
- iframe
`));
});
+
+it('should not include inert elements', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/36938' } }, async ({ page }) => {
+ await page.setContent(`
+ <button>Hi</button>
+ <button inert>Hello</button>
+ <div inert>
+ <button>Yay</button>
+ <p>Some text</p>
+ </div>
+ <p>Visible <span inert>inert</span> text</p>
+ <button><span inert>Save</span></button>
+ `);
+
+ await checkAndMatchSnapshot(page.locator('body'), `
+ - button "Hi"
+ - paragraph: Visible text
+ - button
+ `);
+});
+
+it('should only include the modal dialog content', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/36938' } }, async ({ page }) => {
+ await page.setContent(`
+ <h1>Title</h1>
+ <button>Outside</button>
+ <dialog id=dialog>
+ <h2>Dialog</h2>
+ <button>Inside</button>
+ <div inert><button>Inert inside</button></div>
+ </dialog>
+ <script>
+ document.getElementById('dialog').showModal();
+ </script>
+ `);
+
+ await checkAndMatchSnapshot(page.locator('body'), `
+ - dialog:
+ - heading "Dialog" [level=2]
+ - button "Inside"
+ `);
+
+ await page.locator('#dialog').evaluate((e: HTMLDialogElement) => e.close());
+ await checkAndMatchSnapshot(page.locator('body'), `
+ - heading "Title" [level=1]
+ - button "Outside"
+ `);
+});
diff --git a/tests/page/page-click-timeout-1.spec.ts b/tests/page/page-click-timeout-1.spec.ts
index ad6b1fec77..561348743b 100644
--- a/tests/page/page-click-timeout-1.spec.ts
+++ b/tests/page/page-click-timeout-1.spec.ts
@@ -35,3 +35,26 @@ it('should timeout waiting for button to be enabled', async ({ page }) => {
expect(error.message).toContain('element is not enabled');
expect(error.message).toContain('retrying click action');
});
+
+it('should timeout waiting for inert element to become non-inert', async ({ page }) => {
+ await page.setContent('<div inert><button onclick="javascript:window.__CLICKED=true;">Click target</button></div>');
+ const error = await page.click('text=Click target', { timeout: 3000 }).catch(e => e);
+ expect(await page.evaluate('window.__CLICKED')).toBe(undefined);
+ expect(error.message).toContain('page.click: Timeout 3000ms exceeded.');
+ expect(error.message).toContain('element is inert');
+ expect(error.message).toContain('retrying click action');
+});
+
+it('should timeout waiting for element outside of a modal dialog', async ({ page }) => {
+ await page.setContent(`
+ <button onclick="javascript:window.__CLICKED=true;">Click target</button>
+ <dialog id=dialog><button>Inside</button></dialog>
+ <script>
+ document.getElementById('dialog').showModal();
+ </script>
+ `);
+ const error = await page.click('text=Click target', { timeout: 3000 }).catch(e => e);
+ expect(await page.evaluate('window.__CLICKED')).toBe(undefined);
+ expect(error.message).toContain('page.click: Timeout 3000ms exceeded.');
+ expect(error.message).toContain('element is inert');
+});
diff --git a/tests/page/page-click.spec.ts b/tests/page/page-click.spec.ts
index cf0ac85c22..34393b94b8 100644
--- a/tests/page/page-click.spec.ts
+++ b/tests/page/page-click.spec.ts
@@ -662,6 +662,39 @@ it('should wait for button to be enabled', async ({ page }) => {
expect(await page.evaluate('__CLICKED')).toBe(true);
});
+it('should wait for element to become non-inert', async ({ page }) => {
+ await page.setContent('<div inert id=container><button onclick="window.__CLICKED=true;"><span>Click target</span></button></div>');
+ let done = false;
+ const clickPromise = page.click('text=Click target').then(() => done = true);
+ await giveItAChanceToClick(page);
+ expect(await page.evaluate('window.__CLICKED')).toBe(undefined);
+ expect(done).toBe(false);
+ await page.evaluate(() => document.getElementById('container').removeAttribute('inert'));
+ await clickPromise;
+ expect(await page.evaluate('__CLICKED')).toBe(true);
+});
+
+it('should wait for modal dialog to close', async ({ page }) => {
+ await page.setContent(`
+ <button onclick="window.__CLICKED=true;">Click target</button>
+ <dialog id=dialog><button onclick="window.__DIALOG_CLICKED=true;">Inside</button></dialog>
+ <script>
+ document.getElementById('dialog').showModal();
+ </script>
+ `);
+ await page.click('text=Inside');
+ expect(await page.evaluate('__DIALOG_CLICKED')).toBe(true);
+
+ let done = false;
+ const clickPromise = page.click('text=Click target').then(() => done = true);
+ await giveItAChanceToClick(page);
+ expect(await page.evaluate('window.__CLICKED')).toBe(undefined);
+ expect(done).toBe(false);
+ await page.evaluate(() => (document.getElementById('dialog') as HTMLDialogElement).close());
+ await clickPromise;
+ expect(await page.evaluate('__CLICKED')).toBe(true);
+});
+
it('should wait for input to be enabled', async ({ page }) => {
await page.setContent('<input onclick="window.__CLICKED=true;" disabled>');
let done = false;
diff --git a/tests/page/page-fill.spec.ts b/tests/page/page-fill.spec.ts
index 5aca6d1229..3e918ab3c3 100644
--- a/tests/page/page-fill.spec.ts
+++ b/tests/page/page-fill.spec.ts
@@ -426,3 +426,55 @@ it('should fill contenteditable with focus handler that collapses selection', {
await page.fill('div[contenteditable]', 'some value');
expect(await page.locator('div[contenteditable]').textContent()).toBe('some value');
});
+
+it('should retry on inert element', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/42967' } }, async ({ page }) => {
+ await page.setContent(`
+ <div inert id=container>
+ <input id=target>
+ </div>
+ <input id=outside>
+ `);
+ await page.focus('#outside');
+ let done = false;
+
+ const promise = page.fill('#target', 'some value').then(() => done = true);
+ await giveItAChanceToFill(page);
+ expect(done).toBe(false);
+ expect(await page.$eval('#target', (i: HTMLInputElement) => i.value)).toBe('');
+ expect(await page.$eval('#outside', (i: HTMLInputElement) => i.value)).toBe('');
+
+ await page.$eval('#container', e => e.removeAttribute('inert'));
+ await promise;
+ expect(await page.$eval('#target', (i: HTMLInputElement) => i.value)).toBe('some value');
+ expect(await page.$eval('#outside', (i: HTMLInputElement) => i.value)).toBe('');
+});
+
+it('should retry on element outside of a modal dialog', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/42967' } }, async ({ page }) => {
+ await page.setContent(`
+ <input id=target>
+ <dialog id=dialog><input id=inside></dialog>
+ <script>
+ document.getElementById('dialog').showModal();
+ </script>
+ `);
+ let done = false;
+
+ await page.fill('#inside', 'inside value');
+ expect(await page.$eval('#inside', (i: HTMLInputElement) => i.value)).toBe('inside value');
+
+ const promise = page.fill('#target', 'some value').then(() => done = true);
+ await giveItAChanceToFill(page);
+ expect(done).toBe(false);
+ expect(await page.$eval('#target', (i: HTMLInputElement) => i.value)).toBe('');
+
+ await page.$eval('#dialog', (e: HTMLDialogElement) => e.close());
+ await promise;
+ expect(await page.$eval('#target', (i: HTMLInputElement) => i.value)).toBe('some value');
+});
+
+it('should fail with a nice error on inert element', async ({ page }) => {
+ await page.setContent(`<div inert><input></div>`);
+ const error = await page.fill('input', 'some value', { timeout: 1000 }).catch(e => e);
+ expect(error.message).toContain('Timeout 1000ms exceeded');
+ expect(error.message).toContain('element is inert');
+});
diff --git a/tests/page/selectors-role.spec.ts b/tests/page/selectors-role.spec.ts
index f7db3bcf10..4afb950abf 100644
--- a/tests/page/selectors-role.spec.ts
+++ b/tests/page/selectors-role.spec.ts
@@ -589,3 +589,169 @@ test('should not match scope by default', async ({ page }) => {
await expect(children).toHaveCount(2);
await expect(children).toHaveText(['child 1', 'child 2']);
});
+
+test('should not match inert elements, unless explicitly asked for', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/36938' } }, async ({ page }) => {
+ await page.setContent(`
+ <button>Hi</button>
+ <button inert>Hello</button>
+ <div inert id=container>
+ <button>Yay</button>
+ <div><button>Nay</button></div>
+ </div>
+ <button><span inert>Save</span></button>
+ <div id=host></div>
+ <div inert id=inert-host></div>
+ <script>
+ function addButton(host, text) {
+ const root = host.attachShadow({ mode: 'open' });
+ const button = document.createElement('button');
+ button.textContent = text;
+ root.appendChild(button);
+ }
+ addButton(document.getElementById('host'), 'Shadow1');
+ addButton(document.getElementById('inert-host'), 'Shadow2');
+ </script>
+ `);
+ expect(await page.getByRole('button').evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
+ `<button>Hi</button>`,
+ `<button><span inert="">Save</span></button>`,
+ `<button>Shadow1</button>`,
+ ]);
+ expect(await page.getByRole('button', { includeHidden: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
+ `<button>Hi</button>`,
+ `<button inert="">Hello</button>`,
+ `<button>Yay</button>`,
+ `<button>Nay</button>`,
+ `<button><span inert="">Save</span></button>`,
+ `<button>Shadow1</button>`,
+ `<button>Shadow2</button>`,
+ ]);
+ await expect(page.getByRole('button', { name: 'Yay' })).toHaveCount(0);
+ await expect(page.getByRole('button', { name: 'Yay', includeHidden: true })).toHaveCount(1);
+
+ // Inert content does not contribute to the accessible name.
+ await expect(page.getByRole('button', { name: 'Save' })).toHaveCount(0);
+ await expect(page.getByRole('button', { name: 'Save', includeHidden: true })).toHaveCount(1);
+
+ await page.locator('#container').evaluate(e => e.removeAttribute('inert'));
+ expect(await page.getByRole('button').evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
+ `<button>Hi</button>`,
+ `<button>Yay</button>`,
+ `<button>Nay</button>`,
+ `<button><span inert="">Save</span></button>`,
+ `<button>Shadow1</button>`,
+ ]);
+});
+
+test('should not match elements outside of a modal dialog', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/36938' } }, async ({ page }) => {
+ await page.setContent(`
+ <button>Outside</button>
+ <dialog id=dialog>
+ <button>Inside</button>
+ <div inert><button>Inert inside</button></div>
+ </dialog>
+ <dialog id=non-modal><button>Non-modal</button></dialog>
+ <script>
+ document.getElementById('dialog').showModal();
+ document.getElementById('non-modal').show();
+ </script>
+ `);
+ expect(await page.getByRole('button').evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
+ `<button>Inside</button>`,
+ ]);
+ expect(await page.getByRole('button', { includeHidden: true }).evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
+ `<button>Outside</button>`,
+ `<button>Inside</button>`,
+ `<button>Inert inside</button>`,
+ `<button>Non-modal</button>`,
+ ]);
+ await expect(page.getByRole('dialog')).toHaveCount(1);
+ await expect(page.getByRole('button', { name: 'Outside' })).toHaveCount(0);
+
+ await page.locator('#dialog').evaluate((e: HTMLDialogElement) => e.close());
+ expect(await page.getByRole('button').evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
+ `<button>Outside</button>`,
+ `<button>Non-modal</button>`,
+ ]);
+});
+
+test('should match the topmost modal dialog', async ({ page }) => {
+ await page.setContent(`
+ <button>Outside</button>
+ <dialog id=outer>
+ <button>Outer</button>
+ <dialog id=inner><button>Inner</button></dialog>
+ </dialog>
+ <div inert>
+ <dialog id=escaping><button>Escaping</button></dialog>
+ </div>
+ <script>
+ document.getElementById('outer').showModal();
+ document.getElementById('inner').showModal();
+ </script>
+ `);
+ expect(await page.getByRole('button').evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
+ `<button>Inner</button>`,
+ ]);
+
+ await page.locator('#inner').evaluate((e: HTMLDialogElement) => e.close());
+ expect(await page.getByRole('button').evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
+ `<button>Outer</button>`,
+ ]);
+
+ // Modal dialog inside an inert subtree is not inert.
+ await page.locator('#outer').evaluate((e: HTMLDialogElement) => e.close());
+ await page.locator('#escaping').evaluate((e: HTMLDialogElement) => e.showModal());
+ expect(await page.getByRole('button').evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
+ `<button>Escaping</button>`,
+ ]);
+});
+
+test('should respect PLAYWRIGHT_SKIP_INERT_CHECK', async ({ page, mode }) => {
+ test.skip(mode !== 'default', 'Env variable is read by the in-process server');
+ process.env.PLAYWRIGHT_SKIP_INERT_CHECK = '1';
+ try {
+ // New page gets a fresh injected script that reads the env variable.
+ const newPage = await page.context().newPage();
+ await newPage.setContent(`
+ <button>Outside</button>
+ <div inert><button>Inert</button></div>
+ <dialog id=dialog><button>Inside</button></dialog>
+ <script>
+ document.getElementById('dialog').showModal();
+ </script>
+ `);
+ expect(await newPage.getByRole('button').evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
+ `<button>Outside</button>`,
+ `<button>Inert</button>`,
+ `<button>Inside</button>`,
+ ]);
+ await newPage.close();
+ } finally {
+ delete process.env.PLAYWRIGHT_SKIP_INERT_CHECK;
+ }
+});
+
+test('should respect PLAYWRIGHT_SKIP_DIALOG_CHECK', async ({ page, mode }) => {
+ test.skip(mode !== 'default', 'Env variable is read by the in-process server');
+ process.env.PLAYWRIGHT_SKIP_DIALOG_CHECK = '1';
+ try {
+ // New page gets a fresh injected script that reads the env variable.
+ const newPage = await page.context().newPage();
+ await newPage.setContent(`
+ <button>Outside</button>
+ <div inert><button>Inert</button></div>
+ <dialog id=dialog><button>Inside</button></dialog>
+ <script>
+ document.getElementById('dialog').showModal();
+ </script>
+ `);
+ expect(await newPage.getByRole('button').evaluateAll(els => els.map(e => e.outerHTML))).toEqual([
+ `<button>Outside</button>`,
+ `<button>Inside</button>`,
+ ]);
+ await newPage.close();
+ } finally {
+ delete process.env.PLAYWRIGHT_SKIP_DIALOG_CHECK;
+ }
+});