Skip to content

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

fix: focus contenteditable element before selecting text in fill() (#39493)

erezcord2cc91950bc1
diff --git a/packages/injected/src/injectedScript.ts b/packages/injected/src/injectedScript.ts
index 1f45866bf5..609fce22a9 100644
--- a/packages/injected/src/injectedScript.ts
+++ b/packages/injected/src/injectedScript.ts
@@ -875,6 +875,7 @@ export class InjectedScript {
textarea.focus();
return 'done';
}
+ (element as HTMLElement | SVGElement).focus();
const range = element.ownerDocument.createRange();
range.selectNodeContents(element);
const selection = element.ownerDocument.defaultView!.getSelection();
@@ -882,7 +883,6 @@ export class InjectedScript {
selection.removeAllRanges();
selection.addRange(range);
}
- (element as HTMLElement | SVGElement).focus();
return 'done';
}
diff --git a/tests/page/page-fill.spec.ts b/tests/page/page-fill.spec.ts
index a891abe762..217a7f395a 100644
--- a/tests/page/page-fill.spec.ts
+++ b/tests/page/page-fill.spec.ts
@@ -404,3 +404,25 @@ it('fill back to back', async ({ page }) => {
await expect(page.locator('id=one')).toHaveValue('first value');
await expect(page.locator('id=two')).toHaveValue('second value');
});
+
+it('should fill contenteditable with focus handler that collapses selection', {
+ annotation: {
+ type: 'issue',
+ description: 'https://github.com/microsoft/playwright/issues/39492'
+ }
+}, async ({ page }) => {
+ await page.setContent(`
+ <div contenteditable="true">initial text</div>
+ <script>
+ const editor = document.querySelector('[contenteditable]');
+ editor.addEventListener('focus', () => {
+ const selection = window.getSelection();
+ if (selection.rangeCount > 0)
+ selection.collapseToEnd();
+ });
+ </script>
+ `);
+
+ await page.fill('div[contenteditable]', 'some value');
+ expect(await page.locator('div[contenteditable]').textContent()).toBe('some value');
+});