javascriptnode.jsgoogle-chrome-devtoolspuppeteerheadless-browser

How to delete existing text from input using Puppeteer?


I'm trying to test amending text in an editable input which contains the title of the current record - and I want to able to test editing such text, replacing it with something else.

I know I can use await page.type('#inputID', 'blah'); to insert "blah" into the textbox (which in my case, having existing text, only appends "blah"), however, I cannot find any page methods1 that allow deleting or replacing existing text.


Solution

  • You can use page.evaluate to manipulate DOM as you see fit:

    await page.evaluate( () => document.getElementById("inputID").value = "")
    

    However sometimes just manipulating a given field might not be enough (a target page could be an SPA with event listeners), so emulating real keypresses is preferable. The examples below are from the informative issue in puppeteer's Github concerning this task.

    Here we press Backspace as many times as there are characters in that field:

    const inputValue = await page.$eval('#inputID', el => el.value);
    // focus on the input field
    await page.click('#inputID');
    for (let i = 0; i < inputValue.length; i++) {
      await page.keyboard.press('Backspace');
    }
    

    Another interesting solution is to click the target field 3 times so that the browser would select all the text in it and then you could just type what you want:

    const input = await page.$('#inputID');
    await input.click({ clickCount: 3 })
    await input.type("Blah");