Skip to content

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

feat(codegen): use the name attribute for more elements (#5376)

Joel Einbinder8ef6cb731e98
diff --git a/src/server/supplements/injected/selectorGenerator.ts b/src/server/supplements/injected/selectorGenerator.ts
index 5b49373dfa..657eae9a32 100644
--- a/src/server/supplements/injected/selectorGenerator.ts
+++ b/src/server/supplements/injected/selectorGenerator.ts
@@ -154,14 +154,15 @@ function buildCandidates(injectedScript: InjectedScript, element: Element): Sele
}
if (element.hasAttribute('aria-label'))
candidates.push({ engine: 'css', selector: `[aria-label=${quoteString(element.getAttribute('aria-label')!)}]`, score: 10 });
- if (element.nodeName === 'IMG' && element.getAttribute('alt'))
- candidates.push({ engine: 'css', selector: `img[alt=${quoteString(element.getAttribute('alt')!)}]`, score: 10 });
+ if (element.getAttribute('alt') && ['APPLET', 'AREA', 'IMG', 'INPUT'].includes(element.nodeName))
+ candidates.push({ engine: 'css', selector: `${element.nodeName.toLowerCase()}[alt=${quoteString(element.getAttribute('alt')!)}]`, score: 10 });
if (element.hasAttribute('role'))
candidates.push({ engine: 'css', selector: `${element.nodeName.toLocaleLowerCase()}[role=${quoteString(element.getAttribute('role')!)}]` , score: 50 });
+
+ if (element.getAttribute('name') && ['BUTTON', 'FORM', 'FIELDSET', 'IFRAME', 'INPUT', 'KEYGEN', 'OBJECT', 'OUTPUT', 'SELECT', 'TEXTAREA', 'MAP', 'META', 'PARAM'].includes(element.nodeName))
+ candidates.push({ engine: 'css', selector: `${element.nodeName.toLowerCase()}[name=${quoteString(element.getAttribute('name')!)}]`, score: 50 });
if (['INPUT', 'TEXTAREA'].includes(element.nodeName) && element.getAttribute('type') !== 'hidden') {
- if (element.getAttribute('name'))
- candidates.push({ engine: 'css', selector: `${element.nodeName.toLowerCase()}[name=${quoteString(element.getAttribute('name')!)}]`, score: 50 });
if (element.getAttribute('type'))
candidates.push({ engine: 'css', selector: `${element.nodeName.toLowerCase()}[type=${quoteString(element.getAttribute('type')!)}]`, score: 50 });
}
diff --git a/test/selector-generator.spec.ts b/test/selector-generator.spec.ts
index e7117cda16..8ae9577a79 100644
--- a/test/selector-generator.spec.ts
+++ b/test/selector-generator.spec.ts
@@ -272,4 +272,11 @@ describe('selector generator', (suite, { mode }) => {
]);
expect(await generate(frame, 'div')).toBe('text=Target');
});
+
+ it('should use the name attributes for elements that can have it', async ({ page }) => {
+ for (const tagName of ['button', 'input', 'textarea']) {
+ await page.setContent(`<form><${tagName} name="foo"></${tagName}><${tagName} name="bar"></${tagName}></form>`);
+ expect(await generate(page, '[name=bar]')).toBe(`${tagName}[name="bar"]`);
+ }
+ });
});