When Selenium Webdriver is being used, few times you will face challenges in handling all Key Board and even some times when using Mouse too. The alternate approach is ROBOT or ACTIONS class
Now, here you learn about Actions & Robot classes:
Example: Single Key action
Actions action = new Actions(driver);
action.sendKeys(Keys.ENTER).build().perform();
Example: Set focus to the userName object
Actions action = new Actions(driver);
driver.findElement(By.name(“userName”)).sendKeys(Keys.ENTER);
Example: Multiple Key action
Actions action = new Actions(driver);
action.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();
Example: Copy entire page content (chord is being used when there is a requirement to use more than one Keys
Actions action = new Actions(driver);
driver.findElement(By.name("body")).sendKeys(Keys.chord(Keys.CONTROL, "a"));
or
Actions action = new Actions(driver);
action.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();
Example: Enter input to Text Field
Using ROBOT - Example: Single Key action
Now, here you learn about Actions & Robot classes:
Example: Single Key action
Actions action = new Actions(driver);
action.sendKeys(Keys.ENTER).build().perform();
Example: Set focus to the userName object
Actions action = new Actions(driver);
driver.findElement(By.name(“userName”)).sendKeys(Keys.ENTER);
Example: Multiple Key action
Actions action = new Actions(driver);
action.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();
Example: Copy entire page content (chord is being used when there is a requirement to use more than one Keys
Actions action = new Actions(driver);
driver.findElement(By.name("body")).sendKeys(Keys.chord(Keys.CONTROL, "a"));
or
Actions action = new Actions(driver);
action.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();
Example: Enter input to Text Field
Actions keyin = new Actions(driver);
keyin.sendKeys("Vasu Chiluveru", Keys.ARROW_DOWN) .build().perform();
or
keyin.sendKeys("Vasu Chiluveru") .build().perform();
Example: Enter input to Text Field (clicking on an element first then sending the string to the application)
Actions keyin = new Actions(driver);
WebElement userName = driver.findElement(By.xpath(xpath_expression));
keyin.sendKeys(userName,Keys.SHIFT,"Vasu Chiluveru") .build().perform();
or
keyin.sendKeys(userName,"Vasu Chiluveru") .build().perform();
Using ROBOT - Example: Single Key action
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_CONTROL);
Using ROBOT - Example: Multiple Key actions
Using ROBOT - Example: Multiple Key actions
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_A);
robot.keyPress(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_CONTROL);