Saturday, December 28, 2013

Mouse And KeyBoard Event Handling Using Selenium WebDriver


Keyboard and Mouse are most usable peripheral devices by which we can interact with webpages.So we need some motivation to galore knowledge on this using Selenium Web Driver.

Basically we have 2 type of things to discuss:

1.Mouse Event
2.KeyBoard Event

1.Mouse Event 

Step 1:

Import Actions and Action class.

import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

Step 2: 

Create a Instance of Actions class

Actions builder=new Actions(driver);

Step 3:

Get the Action using build(),this method use to bind multiple action into a one action.

Action selectAllText=builder.moveToElement(txtBoxElement).
                                            sendKeys(txtBoxElement, "test").
                                                      doubleClick(txtBoxElement).build(); 

Here we try to send text into the web element which is a textbox field and double on it so text should be selected.
  
 Step 4:

To execute this action we need perform().

selectAllText.perform();


2.KeyBoard Event

The keyboard interactions API will (first) support keyboard actions without a provided element. The additional work to focus on an element before sending it keyboard events will be added later on.

Step 1:

Import Actions and Action class.

import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

Step 2: 

Create a Instance of Actions class

Actions builder=new Actions(driver);

Step 3:

Get the Action using build(),this method use to bind multiple action into a one action.

Action writeCapital=builder.keyDown(Keys.SHIFT).
                                      sendKeys(driver.findElement(By.name("email")),"abc").
                                              keyUp(Keys.SHIFT).build().perform();

Here we try to hold Shift key and send text, by this way we get the capital letter into the webelement field(basically it is a textbox field).

 Step 4:

To execute this action we need perform().

writeCapital.perform();

Keep in mind:

1.When  KeyDown() method use for particular key then should be release this key using keyUp() method.
2.KeyDown() method is only used for modifier keys Shift,Alt,Control

 


 

2 comments:

  1. i find ur posts to be very useful,thank u..

    request u to post more samples for keyboard events using Actions class

    ReplyDelete