I’m working on a Puppeteer project and I’m stuck on how to change text in an input field that already has content. I want to test editing the title of a record, but I can’t figure out how to replace the existing text.
I know I can add text to the end of what’s already there using page.type(), but that’s not what I need. Is there a way to clear out the old text and put in something new? Or maybe just replace everything in one go?
I’ve looked through the Puppeteer docs but couldn’t find anything obvious. Any tips or tricks would be super helpful!
Here’s a quick example of what I’ve tried:
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
// This adds text to the end
await page.type('#titleInput', 'New Title');
// But how do I replace the existing text?
I’ve dealt with this exact issue in my Puppeteer projects! Here’s what worked for me:
You can use a combination of page.click() to focus the input field, keyboard.down() and keyboard.up() to simulate pressing Ctrl+A to select all text, and then keyboard.press() to hit Backspace. After that, just type your new text.
This approach mimics how a user would manually edit the field. It’s been reliable for me across different websites and input types. Just remember to adjust the selector to match your specific input field.
Another approach you could try is using the page.evaluate() method to directly manipulate the input field’s value. This can be more efficient and reliable in some cases. Here’s how you might do it:
This method bypasses the need to simulate keystrokes and can be faster. It’s particularly useful if you’re dealing with complex input fields or dynamic web applications where direct DOM manipulation is more reliable.
Remember to adjust the selector to match your specific input field. Also, depending on the website, you might need to trigger a change event after setting the value to ensure the application recognizes the change: