Handling keyboard events in Selenium

Posted By :Nidhi Ojha |31st May 2020

As we know the sendKeys() method which replicates the keyboard typing action on a textbox or input type element. But this method is not adequate for handling complex keyboard actions. For this, Selenium has an Actions class which gives various methods for Keyboard interactions. In this blog, we will learn the three actions for handling keyboard action – keyDown(), keyUp() and sendKeys() in addition to their overloaded method implementations.

Actions Class Method for Keyboard Interaction:


1. keyDown(Keys modifierKey)-
The keyDown(Keys modifierKey) method accepts the modifier Keys as parameter (Shift, Alt and Control Keys – it modifies the motive of other keys, thus the name). It is pre-owned to replicates the action of pressing a modifier key, without releasing. The anticipated values for the keyDown() method are – Keys.SHIFT, Keys.ALT and Keys.CONTROL only, passing key along with these results in IllegalArgumentException.


2. keyDown(WebElement element, Keys modifierKey)-
This different implementation of keyDown() method in which the modifier key press action is performed on a WebElement.

3. keyUp(Keys modifierKey)-
The keyUp() method is adequated to simulate the modifier key-up or key-release action. This method adheres to a preceeding key press action.


4. keyUp(WebElement element, Keys modifierKey)-
This implementation of keyUp() method performs the key-release action on a web element.


5. sendKeys(CharSequence KeysToSend)-
The sendKeys(CharSequence KeysToSend) method sends a sequence of keys to the currently focused web element. Here, we must note that it is various from the webElement.sendKeys() method. The Actions sendKeys(CharSequence KeysToSend) is particularly benefecial when dealing with modifier keys as it doesn’t release those keys when passed(resulting in correct behaviour) unlike the webElement.sendKeys() method.


6. sendKeys(WebElement element, CharSequence KeysToSend)-
This implementation of sendKeys() method is used to send a sequence of keys to a web element.


We will implement above implemenations with the help of code.


Code snippet for Keyboard Actions


//WebElement to which the keyboard actions are performed WebElement textBoxElement = driver.findElement(By Locator of textBoxElement); //Creating object of Actions class Actions builder = new Actions(driver); //Creating an action to input text in CAPS. Action typeInCAPS = builder.keyDown(textBoxElement, Keys.SHIFT) .sendKeys(textBoxElement,"https://artificialintelligence.oodles.io/") .keyUp(textBoxElement, Keys.SHIFT) .build(); //Performing the typeInCAPS action typeInCAPS.perform();

About Author

Nidhi Ojha

Nidhi is certified in Manual Testing and SQL. She has done B.tech in Electronics and Communication branch, apart from this she loves to travel to different places.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us