67

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', 'test@example.com');

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?

Grant Miller
  • 19,410
  • 15
  • 108
  • 135
choasia
  • 8,394
  • 4
  • 34
  • 51

5 Answers5

98

Just set value of input like this:

await page.$eval('#email', el => el.value = 'test@example.com');

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.waitFor('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();
})();
Everettss
  • 13,024
  • 7
  • 63
  • 89
61

another way doing

await page.focus('#email')
await page.keyboard.type('test54')
Sarath Ak
  • 5,066
  • 35
  • 37
  • 4
    This worked. The thing is, in some forms, there is a trigger on keypress that does something. If you just set the input field value, this trigger is not run and the form submit does not work correctly. – marlar Jan 26 '20 at 13:41
59

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'

Andrew
  • 1,910
  • 1
  • 12
  • 9
  • Hello, dear Andrew! Could you please point me to the source where I can read more about this syntax? – JacekDuszenko Sep 24 '18 at 23:18
  • 2
    Hi Mrrobot, it's been a while since I've looked at this and can't really remember where I got it from. A quick look at the docs shows the prototype expected for this and the optional '...args'. None of the examples show it that clearly but it is documented [here](https://pptr.dev/#?product=Puppeteer&version=v1.8.0&show=api-pageevalselector-pagefunction-args-1). – Andrew Sep 25 '18 at 04:20
  • 1
    This is super useful. I was totally confused why simply changing the string value to a local variable didn't work. Great extension and super helpful. – miken Aug 05 '19 at 20:02
  • Solve my problem, thanks! – Arst Mar 31 '21 at 07:00
7

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 = 'test@example.com';
});
Grant Miller
  • 19,410
  • 15
  • 108
  • 135
0

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);
}
Cryptc
  • 702
  • 1
  • 7
  • 9