KeyBoard Events in Selenium:

 

  • When selenium Webdriver is used, browser controls and application types of the WebDriver by reference variables, meaning that the WebDriver reference variable can identify any web element on the page.
  • But it does not have the ability to handle all keyboard and mouse events such as right-click, drag and drop, clickAndHold etc.

 

Ways To Handle Keyboard Keys:

  1. Handle Keyboard Keys using Action class.
  2. Handle Keyboard Keys using sendkeys chord.
  3. Handle Keyboard keys using Robot class.

 

1. Handle Keyboard Keys using Action class:

 

Actions Class Method for Keyboard:

keyDown and keyUp are the main methods in KeyBoard Events in Selenium Webdriver Actions class.

  • public Actions keyDown(Keys theKey) : Performs a modifier key press (SHIFT,Keys.ALT or Keys.CONTROL) to Handle keyDown operation.
  • public Actions keyDown(WebElement element, Keys theKey) : Performs a modifier key press (SHIFT,Keys.ALT or Keys.CONTROL) after focusing on an element perform keyDown using WebElement.
  • public Actions keyUp(Keys theKey) : Performs a modifier key release (SHIFT,Keys.ALT or Keys.CONTROL) to Handle keyUp operation.
  • public Actions keyUp(WebElement element, Keys theKey) : performs a modifier key release after focusing on an element to perform keyUp operation.
  • public Actions sendKeys(java.lang.CharSequence… keysToSend) : The key sends the active element to the key, it is actively different from calling sendKeys two passes (CharSequence…) on an active element in two ways: Modifiers are not included in this call, and no one is able to focus the element again. Do not try. Then we will send some sendKeys(Keys.TAB) to switch the elements.
  • public Actions sendKeys(WebElement element, java.lang.CharSequence… keysToSend) : Sends keys to the given element using sendKeys.

 

Handle Single Keyboard Key using Action class:

  • Press ENTER using sendKeys with the help of Action Class.

 

Handle multiple Keyboard keys using Actions class:

 

Example: Handle Single / Multiple Keys using Action class:

 

2. Handle Keyboard Keys using sendkeys chord:

 

Handle Single Keyboard Key using Sendkeys:

 

Handle multiple Keyboard keys using chord:

  • When we want to Press multiple keys that time we use chord.

 

Example: Handle Single / Multiple Keys using Sendkeys / Chord:

 

3. Handle Keyboard keys using Robot class.

 

Handle Keyboard keys using Robot class:

  • In Robot Class using keyPress Method we handle KeyBoard events.

 

Example of Handle Keyboard keys using Robot class: