puppeteer: [Bug]: `keyboard.press('Tab')` does not set active element
Bug expectation
I expect pressing the Tab key to behave as it does in the browser: focus the next focusable element in the document.
Instead, it does not set an active element.
Bug behavior
- Flaky
Minimal, reproducible example
import puppeteer from 'puppeteer';
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent('<input id="login">');
await page.waitForSelector('#login');
await page.keyboard.press('Tab');
const id = await page.evaluate(() => document.activeElement?.id);
if (id !== 'login') {
throw new Error('login is not active')
}
await browser.close();
Error string
login is not active
Puppeteer configuration
Puppeteer version
19.4.1
Node version
18.12.0
Package manager
npm
Package manager version
8.19.2
Operating system
macOS
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Comments: 30
@JakobJingleheimer you can use
page.exposeFunctionto expose a callback to the app and then synchronize based on that.We found the cause of both issues (random/chaotic field focus and wrong sub-field focus within date/datetime fields): React’s reconciliation.
TLDR: The workaround to set a tiny delay for Puppeteer whenever the DOM will be updated and Puppeteer will interact with that update.
Reconciliation is async process that happens at the very end of React’s rendering phase, as a sort of clean-up step; it’s very fast (well fast enough to finish before a human can do anything), but Puppeteer is faster—effectively jumping the gun (in Puppeteer’s defence—there is no gun, just “ready, set, __”).
Trying to come up with a simple reproduction was doomed from the start: It does not re-pro in a simple example because the issue requires a lot of DOM updates in order to cause reconciliation to take longer than Puppeteer.
I think an ideal solution would be to expose some way to inform Puppeteer things are “go”. This is possible to know via react’s
componentDidMountandcomponentDidUpdate(react renders from leaves to root, so a “page” as a class component would call these after all its content has finished). Would it be possible (and not excessively difficult) to broadcast an event for which Puppeteer would listen and then “go”?This would also avoid needing
waitForSelector(which continuously probes for a match on the provided selector).No, I don’t think Puppeteer builds lists of focusable elements. You can take a peek at Puppeteer’s code and see commands it sends to the browser using
DEBUG=puppeteer:*.keyboard.press('TAB')just sends https://chromedevtools.github.io/devtools-protocol/tot/Input/#method-dispatchKeyEvent and the browser does its own thing.