Typing Enter/Return key in Selenium.


We can type Enter/Return key in Selenium. We shall use the sendKeys method and pass Keys. ENTER as an argument to the method. Also, we can use pass Keys. RETURN as an argument to the sendKeys method for the same purpose.

To use the Keys class, we have to incorporate import org.openqa.selenium.Keys to the code. Let us type Enter/Return after inputting text within the below edit box.

Example

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
public class TypeEnter{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      // identify element
      WebElement m=driver.findElement(By.id("gsc−i−id1"));
      m.sendKeys("Java");
      // type enter with sendKeys method and pass Keys.ENTER
      m.sendKeys(Keys.ENTER);
      driver.quit();
   }
}

Example

Code Implementation with Keys.RETURN.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
public class TypeReturn{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      // identify element
      WebElement m=driver.findElement(By.id("gsc−i−id1"));
      m.sendKeys("Java");
      // type enter with sendKeys method and pass Keys.RETURN
      m.sendKeys(Keys.RETURN);
      driver.quit();
   }
}

Updated on: 31-Oct-2023

20K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements