Puppeteer is a Node.js framework used for headless browser testing via the Chrome DevTools Protocol. For form-based web apps, the type() method helps automate text input, simulating real user interactions.
Overview
The type() method in Puppeteer is used to simulate typing text into an input field, similar to how a user would enter data manually. It helps automate form interactions, making it essential for testing workflows that involve user input.
Use Cases of the type() Method:
- Filling out login or registration forms
- Entering search queries in input fields
- Typing messages in chat applications
- Simulating typing delays to mimic real user behavior
- Automating data entry for repetitive form submissions
This article covers Puppeteer’s type() method, including Page.type() and Keyboard.type(), with their parameters, return values, and usage examples for automating text input.
What is Puppeteer Type Method: type()
In Puppeteer, the `type()` method is used to simulate keyboard input on an element. It allows you to programmatically enter text or key sequences into input fields, text areas, or any other focusable element on a web page.
Puppeteer provides two type() methods:
- `page.type()`: This method is a high level method that combines both keyboard input and a series of trigger events, such as `keydown`, `keypress`, and `keyup`.This method is useful when implementing a more realistic user journey.
- `page.keyboard.type()`: This method is a low level method that directly sends the key sequences to the focussed element on the page. Since the type event is focussed on the element, this method is faster as compared to the `page.type()` method.
Page.type() method in Puppeteer
In most cases, it is recommended that the page.type() method is used.
Parameters of Page.type() method
Parameter | Type | Description |
---|---|---|
selector | string | Set to the selector where you want to enter text. |
text | string | Value to be set in the field. |
options | { delay: number; } | Optional: Set to numeric value in milliseconds to mimic user delay. |
Returns of Page.type() method
Returns a Promise<void>
Example of Page.type() method
Here’s an example of page.type() method in Puppeteer.
``` await page.type('#textarea, 'Hello'); // Types instantly await page.type('#textarea', 'World', {delay: 120}); // Types slower, like a user ```
Keyboard.type() Method in Puppeteer
For situations where you need to insert text without taking event handling into consideration, use the `page.keyboard.type()`.
Parameters of Keyboard.type()
Parameter | Type | Description |
---|---|---|
text | string | Value to be set in the field. |
options | { delay: number; } | Optional: Set to numeric value in milliseconds to mimic user delay. |
Returns of keyboard.type() method
Returns a Promise<void>
Example of keyboard.type() method
Here’s an example of keyboard.type() method in Puppeteer.
``` await page.keyboard.type('Hey'); // Types instantly await page.keyboard.type('World', {delay: 120}); // Types slower, like a user ```
Use the type() method in Puppeteer
This example demonstrates how to log in to the website https://the-internet.herokuapp.com/login by entering a username and password using the page.type() method, followed by simulating the Enter key press with page.keyboard.press().
The following steps describe the logic for each step of the script:
1. Add the Puppeteer dependency, open a new browser, and then go to the website:
const puppeteer = require('puppeteer'); async function run() { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://the-internet.herokuapp.com/login');
2. Type the username using the `page.type()` method:
// Type username await page.waitForSelector('#username'); await page.type('#username', 'tomsmith');
3. Type the password using the `page.type()` method:
// Type password await page.waitForSelector('#password'); await page.type('#password', 'SuperSecretPassword!');
4. Submit the form using the `page.keyboard.press()` method:
// Submit the form await page.keyboard.press('Enter'); // Wait for navigation to complete await page.waitForNavigation();
5. Add the logic to verify if login was successful:
// Check if login was successful const isLoggedIn = await page.evaluate(() => { return window.location.href === 'https://the-internet.herokuapp.com/secure'; }); if (isLoggedIn) { console.log('Login successful!'); // Further actions after successful login can be added here } else { console.log('Login failed.'); }
6. Take a screenshot and close the browser:
// Capture a screenshot after login (optional) await page.screenshot({ path: 'login_screenshot.png' }); await browser.close();
Run Puppeteer Tests on Real Devices
The complete script of Puppeteer Type Command example is as follows:
const puppeteer = require('puppeteer'); async function run() { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://the-internet.herokuapp.com/login'); // Type username await page.waitForSelector('#username'); await page.type('#username', 'tomsmith'); // Type password await page.waitForSelector('#password'); await page.type('#password', 'SuperSecretPassword!'); // Submit the form await page.keyboard.press('Enter'); // Wait for navigation to complete await page.waitForNavigation(); // Check if login was successful const isLoggedIn = await page.evaluate(() => { return window.location.href === 'https://the-internet.herokuapp.com/secure'; }); if (isLoggedIn) { console.log('Login successful!'); // Further actions after successful login can be added here } else { console.log('Login failed.'); } // Capture a screenshot after login (optional) await page.screenshot({ path: 'login_screenshot.png' }); await browser.close(); } run();
After your run the script, the `login_screenshot.png` can be seen as follows:
Conclusion
Puppeteer offers many more methods that make it easier to create test scripts for your use cases easily. Its headless mode offers improved performance, efficiency, scalability, and flexibility for automating browser-based tasks. Most web applications need to be tested on varied devices, OS, and browsers for a seamless experience, which might be something Puppeteer expanse might not cover.
With BrowserStack, you gain the ability to use a device cloud that is compatible with Puppeteer. This cloud empowers you to execute cross browser Puppeteer tests in parallel across multiple browsers and devices simultaneously, 3500+ real devices and browsers available on the cloud.
Puppeteer is a Node.js library that lets you control Chrome or Chromium over the DevTools Protocol. Learn how to install and setup Puppeteer using npm, run your first test, and some best practices while using it.
For web applications that require entering user input or text, Puppeteer provides the type() method. Use the type() method to simulate user input or keyboard interactions. Learn how to use the type() method to enter information on a login screen.