As you already know, puppeteer is headless chrome which can automate everything a user does with a browser.
Today, we will discuss how to automate keyboard input which could perhaps be in a form field, email or anywhere else.
Just as a user would normally do;
- open a browser,
- new tab/page
- open url
- and then type something and
- close browser when done
Let us discuss the following methods of the keyboard class;
keyboard.type(text,[Options])
This method types-in or inputs the text passed as parameter in a field selector (For example; “hello world”). Options can equally be passed to modify it’s operation.
keyboard.down(key,[Options])
As the name implies, this method handles only the key-down event. Which takes as param the key to be pressed down and options. For example, KeyC
keyboard.press(key,[Options])
This method handles both the key-down and key-up event to form a complete key-press.
keyboard.up(key)
As the name implies, this method handles only the key-up event. Which takes as param the key to be release-up and options.
Now, let’s see how they work in code;
server.js
const puppeteer = require('puppeteer');
(async () => {const browser = await puppeteer.launch() //launch headless browserconst page = await browser.newPage() //new page/tabawait page.goto('https://www.rapidtables.com/tools/notepad.html') //web linkawait page.focus('textarea') //focus on selector which is the text area fieldawait page.keyboard.type('Hello World');await page.keyboard.press('Enter');await page.keyboard.type('Welcome to Google Puppeteer');await page.keyboard.press('Enter');await page.keyboard.type('Feel the magic ✨🎁');await page.screenshot({ path: './uploads/image.png' });await browser.close() //close browserconsole.log ('done')})()
The above code simply opens notepad on the web and then types in some text using the methods explained above.
OUTPUT
Run script:
Check uploads folder
To read more about the keyboard class of the puppeteer library, you can check out their official doc at : https://pptr.dev/
Thanks for coding with us.
Comments
Post a Comment
Please do not enter any spam link in the comment box.