Using Puppeteer to submit a form with a search bar

I’m trying to use Puppeteer to submit a form with a search bar and button. I’ve got the code to enter text in the search field, but I can’t get it to actually submit the form. Here’s what I’ve tried:

const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.goto('http://localhost:3000');
await page.focus('#search');
await page.type('john doe');
await page.press('Enter');

This enters the search text, but doesn’t trigger the search. The form works when I manually hit enter in the browser. How can I get Puppeteer to submit the form automatically?

My form looks like this:

<form onSubmit={this.handleSearch}>
  <input
    id='search'
    type='text'
    value={this.state.query}
    onChange={this.handleChange}
  />
  <button type='submit'>Search</button>
</form>

I’ve also tried using page.$('#search-form') and calling submit() on it, but that just clears the form instead of triggering the search. Any ideas on how to get this working?

I’ve encountered similar issues with Puppeteer before. From my experience, the most reliable way to submit a form is to click the submit button directly. Try this approach:

await page.click('button[type="submit"]');

If that doesn’t work, you might need to wait for the form to be fully loaded before interacting with it:

await page.waitForSelector('#search');
await page.type('#search', 'john doe');
await page.click('button[type="submit"]');

Another trick I’ve found useful is to evaluate the form submission directly in the page context:

await page.evaluate(() => {
  document.querySelector('form').submit();
});

These methods have worked well for me in various projects. Let me know if any of these solutions resolve your issue!

I’ve dealt with this exact problem in a recent project. What worked for me was simulating a mouse click on the submit button. Here’s the code snippet that did the trick:

await page.click('button[type="submit"]');

If that doesn’t work, you might need to force the form submission programmatically:

await page.evaluate(() => {
  document.querySelector('form').dispatchEvent(new Event('submit'));
});

This approach bypasses any client-side validation and directly triggers the form submission event. Just make sure your form is fully loaded before executing these commands. Hope this helps solve your issue!