I’m working on a project where I need to test editing text in an input field. The field already has some text in it, which is the title of the current record. I want to completely replace this text with something new.
I’ve figured out how to add text to the input using page.type(), but it only adds the new text at the end. What I really need is a way to clear out the existing text first, then put in the new stuff.
I’ve looked through the Puppeteer docs, but I can’t seem to find any methods that let me delete or replace text that’s already there. Does anyone know how to do this? Maybe there’s a trick I’m missing or a different approach I should be using?
Here’s a basic example of what I’m trying to do:
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
// This just adds text to the end
await page.type('#title-input', 'New Title');
// What I need is something like:
// await page.clearAndType('#title-input', 'New Title');
await browser.close();
I’ve got a nifty trick for this that’s worked wonders for me. Try using the page.$eval() method combined with the value property. It’s quick and efficient:
This approach directly manipulates the input’s value, clearing it out completely before you type in the new text. It’s been super reliable in my experience, even on tricky pages where other methods sometimes fall short.
One word of caution though - make sure your selector is spot on. If it’s off, you might end up clearing the wrong field or not clearing anything at all. Double-check your selectors if things aren’t working as expected.
A reliable approach I’ve used for this scenario is combining page.focus() and keyboard.press(). Here’s how you can implement it:
await page.focus(‘#title-input’);
await page.keyboard.press(‘End’);
for (let i = 0; i < 100; i++) {
await page.keyboard.press(‘Backspace’);
}
await page.type(‘#title-input’, ‘New Title’);
This method focuses on the input, moves the cursor to the end, then repeatedly presses backspace to clear the existing content before typing the new text. Although it’s not the most elegant solution, it effectively mimics user behavior and works consistently across different websites. Adjust the loop count if you are dealing with longer text fields.