Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
223 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);
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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...