How to fill an input field using Puppeteer?

Javascriptnode.jsGoogle Chrome-DevtoolsPuppeteerE2e Testing

Javascript Problem Overview


I'm using Puppeteer for E2E test, and I am now trying to fill an input field with the code below:

await page.type('#email', '[email protected]');

It worked, but I found the email address was typed into the field one character by one character as if a real human being was typing.

Is it possible to fill the input field with the email address all at one time?

Javascript Solutions


Solution 1 - Javascript

Just set value of input like this:

await page.$eval('#email', el => el.value = '[email protected]');

Here is an example of using it on Wikipedia:

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://en.wikipedia.org', {waitUntil: 'networkidle2'});

    await page.waitForSelector('input[name=search]');

    // await page.type('input[name=search]', 'Adenosine triphosphate');
    await page.$eval('input[name=search]', el => el.value = 'Adenosine triphosphate');

    await page.click('input[type="submit"]');
    await page.waitForSelector('#mw-content-text');
    const text = await page.evaluate(() => {
        const anchor = document.querySelector('#mw-content-text');
        return anchor.textContent;
    });
    console.log(text);
    await browser.close();
})();

Solution 2 - Javascript

another way doing

await page.focus('#email')
await page.keyboard.type('test54')

Solution 3 - Javascript

To extend the accepted answer above, you can use $eval with locally scoped variables too,

const myLocalValue = 'Adenosine triphosphate';    
await page.$eval('input[name=search]', (el, value) => el.value = value, myLocalValue);

This will take 'myLocalValue' from the local scope, and pass it into the browser scope as 'value'

Solution 4 - Javascript

page.evaluate()

You can use page.evaluate() to assign the email string to the value attribute of the element:

await page.evaluate(() => {
  const email = document.querySelector('#email');
  email.value = '[email protected]';
});

Solution 5 - Javascript

The selected answer didn't work for me in the latest version of Puppeteer(10.x). Instead what worked for me were the following commands.

test('should login', async () => {
const page = await browser.newPage();
page.setDefaultTimeout(6000);
await page.goto('https://www.saucedemo.com/');
await page.waitForSelector('#user-name');
await page.type('#user-name', 'standard_user');
await page.type('#password', 'secret_sauce');
await page.click('#login-button');
await page.waitForSelector('#contents_wrapper');});

Solution 6 - Javascript

For Puppeteer Sharp, the syntax is a little different, and there are 2 ways to do it, but one is better than the other. Here is a full example:

static async Task Main(string[] args)
{
	await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision);

	await using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true, Product = Product.Chrome }))
	await using (var page = await browser.NewPageAsync())
	{
		try
		{
			await page.GoToAsync(urlString);
			await page.WaitForSelectorAsync("#btnSubmit");

			await ReplaceText(page, "#inputUsernameId", usernameString);
			await ReplaceText(page, "#inputPasswordId", passwordString);

			await page.ClickAsync("#btnSubmit");
			await page.WaitForNavigationAsync();  // Optional, if the page is changing			
		}
		catch (Exception ex)
		{
			Console.WriteLine(ex);
			// Handle me / Log me
			throw;
		}
	}
}

private static async Task ReplaceText(Page page, string selector, string replacementValue)
{
	await page.WaitForSelectorAsync(selector).ConfigureAwait(false);
	await page.EvaluateExpressionAsync($"document.querySelector(\"{selector}\").value = \"{replacementValue}\"").ConfigureAwait(false);

	// Alternative older method below (not as reliable with async, but works):
	// await ele.FocusAsync().ConfigureAwait(false);
	//
	// await page.Keyboard.DownAsync("Control").ConfigureAwait(false);
	// await ele.PressAsync("A").ConfigureAwait(false);
	// await page.Keyboard.UpAsync("Control").ConfigureAwait(false);
	// await ele.PressAsync("Backspace").ConfigureAwait(false);
	// 	  
	// await ele.TypeAsync(replacementText).ConfigureAwait(false);
	// await ele.PressAsync("Tab").ConfigureAwait(false);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchoasiaView Question on Stackoverflow
Solution 1 - JavascriptEverettssView Answer on Stackoverflow
Solution 2 - JavascriptSarath AkView Answer on Stackoverflow
Solution 3 - JavascriptAndrewView Answer on Stackoverflow
Solution 4 - JavascriptGrant MillerView Answer on Stackoverflow
Solution 5 - JavascriptNikolay AdvolodkinView Answer on Stackoverflow
Solution 6 - JavascriptCryptcView Answer on Stackoverflow