Keyboard Actions in Selenium WebDriver

Keyboard Actions in Selenium WebDriver

In our beginner’s tutorials, we have seen the sendKeys() method which simulates the keyboard typing action on a textbox or input type element. But this method is not sufficient for handling complex keyboard actions. For this, Selenium has an Actions class which provides different methods for Keyboard interactions. In this tutorial, we wil be studying the three actions for handling keyboard action – keyDown(), keyUp() and sendKeys() along with their overloaded method implementations.

Actions Class Method for Keyboard Interaction

  1. keyDown(Keys modifierKey)-
    The keyDown(Keys modifierKey) method takes the modifier Keys as parameter (Shift, Alt and Control Keys – that modifies the purpose of other keys, hence the name). It is used to simulate the action of pressing a modifier key, without releasing. The expected values for the keyDown() method are – Keys.SHIFT, Keys.ALT and Keys.CONTROL only, passing key other than these results in IllegalArgumentException.
  2. keyDown(WebElement element, Keys modifierKey)-
    This another implementation of keyDown() method in which the modifier key press action is performed on a WebElement.
  3. keyUp(Keys modifierKey)-
    The keyUp() method is used to simulate the modifier key-up or key-release action. This method follows 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 is used to send a sequence of keys to a currently focussed web element. Here, we need to note that it is different from the webElement.sendKeys() method. The Actions sendKeys(CharSequence KeysToSend) is particularly helpful 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.

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);

//Generating an action to type a text in CAPS
Action typeInCAPS = builder.keyDown(textBoxElement, Keys.SHIFT)
.sendKeys(textBoxElement, "artOfTesting")
.keyUp(textBoxElement, Keys.SHIFT)
.build();
//Performing the typeInCAPS action
typeInCAPS.perform();

That’s all we have in this post, comment below if you have any questions. Also please share this post with your friends and don’t forget to check our Step-by-Step selenium tutorial here.

Selenium with Java – Complete Tutorial

От QA genius

Adblock
detector