My Thoughts: Sending special characters and key events to WebDriver using sendKeys() method

Sunday, December 16

Sending special characters and key events to WebDriver using sendKeys() method

There are times at which we would like to send special characters (Enter , F5, Ctrl, Alt etc..) to webdriver from our script. This can be done by using sendKeys method itself. For this purpose we will use the Keys  method as parameter to the sendKeys method.

Syntax :
//Sending F5 key
driver.findElement(By.id("name")).sendKeys(Keys.F5);

//Sending arrow down key 
driver.findElement(By.id("name")).sendKeys(Keys.ARROW_DOWN);

//sending pagedown key from keyboard
driver.findElement(By.id("name")).sendKeys(Keys.PAGE_DOWN);

//sending space key 
driver.findElement(By.id("name")).sendKeys(Keys.SPACE);

//sending tab key
driver.findElement(By.id("name")).sendKeys(Keys.TAB);

//sending alt key
driver.findElement(By.id("name")).sendKeys(Keys.ALT);
We can also send the pressable keys as Unicode PUA(Privtae User Area)  format . So the above samples can be rewritten as below :
sendKeys(Keys.F5) == sendKeys("\uE035")

sendKeys(Keys.PAGE_DOWN) == sendKeys("\uE00F")

sendKeys(Keys.ARROW_DOWN) == sendKeys("\uE015")

sendKeys(Keys.SPACE) == sendKeys("\uE00D")

sendKeys(Keys.TAB) == sendKeys("\uE004")

sendKeys(Keys.ALT) == sendKeys("\uE00A")
Here is the sample program for logging into Facebook :
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Sendkeys {
 
WebDriver driver;
 
@BeforeTest
 public void start(){
  driver = new FirefoxDriver();
 }

@Test
public void sendkeysmethod(){
 //Load facebook login page
 driver.get("https://facebook.com");
 
 //Refresh the page 
 //We can also refresh like below 
 //driver.findElement(By.name("email")).sendKeys("\uE035")
 driver.findElement(By.name("email")).sendKeys(Keys.F5);
 
 //Fillup Emailadress and Password fields
 driver.findElement(By.name("email")).sendKeys("EmailAddress");
 driver.findElement(By.name("pass")).sendKeys("password");
 
 //Sending Enter key so that facebook login credentials will be authenticated
 driver.findElement(By.name("pass")).sendKeys(Keys.ENTER);
 
    }
}

Reference :

http://www.w3.org/TR/2012/WD-webdriver-20120710/#typing-keys
http://code.google.com/p/selenium/wiki/GettingStarted
http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/Keys.html

1 comment:

  1. Thanks a lot for the article - it really helped me ;)

    ReplyDelete