How do I simulate keyboard events (e.g., key press, keydown) in Puppeteer?
Davide S
davide s profile pic

Simulating keyboard events, such as key presses or keydown events, in Puppeteer involves using thepage.keyboard object to emulate keyboard interactions. Here's a detailed explanation of how to simulate keyboard events in Puppeteer: 1. Launching a new browser instance and creating a new page:

1
2
3
4
5
6
7
8
9
10
11
12
13

   const puppeteer = require('puppeteer');

   (async () => {
     const browser = await puppeteer.launch();
     const page = await browser.newPage();

     // Perform actions with the page here

     // Close the browser
     await browser.close();
   })();
   

This code sets up a basic Puppeteer script. It launches a new headless browser instance and creates a new page to work with. 2. Simulating key presses usingpage.keyboard.press(): To simulate a key press, you can use thepage.keyboard.press() method and pass the key code or key symbol as an argument.

1
2
3

   await page.keyboard.press('Enter');
   

In this example,page.keyboard.press() is used to simulate pressing the Enter key. You can pass the key symbol or the key code for the desired key. 3. Simulating keydown events usingpage.keyboard.down(): If you want to simulate a keydown event, you can use thepage.keyboard.down() method to press a key and keep it held down until a corresponding keyup event is triggered.

1
2
3

   await page.keyboard.down('Shift');
   

This code simulates pressing and holding down the Shift key. Remember to release the key usingpage.keyboard.up() later to trigger the keyup event. 4. Simulating keyup events usingpage.keyboard.up(): To simulate a keyup event and release a pressed key, use thepage.keyboard.up() method.

1
2
3

   await page.keyboard.up('Shift');
   

This code simulates releasing the Shift key, which was previously pressed usingpage.keyboard.down(). 5. Typing text usingpage.keyboard.type(): To simulate typing text into an element, you can use thepage.keyboard.type() method.

1
2
3

   await page.keyboard.type('Hello, World!');
   

In this example, the text "Hello, World!" is simulated to be typed into the currently focused element on the page. By following these steps, you can simulate keyboard events in Puppeteer. Whether you need to simulate key presses, keydown events, keyup events, or typing text, Puppeteer'spage.keyboard object provides the necessary methods (press(),down(),up(),type()) to emulate keyboard interactions. This enables you to automate user input on web pages as part of your Puppeteer scripts.