Use Shift Right and Shift Left properly in Selenium

Overview in 3 lines

problem

If you want to keyDown using Selenium in Java, write the following code.

public void sendKey(WebDriver webDriver, CharSequence... keys) {
  WebElement element = webDriver.findElement(By.className("hoge"))
  element.sendKeys(keys);
}

WebElement.sendKeys takesCharSequence ...as an argument, but often uses the provided enumKeys. However, be careful if you want to use the same function keys on the left and right, such as the right Shift key / left Shift key.

The implementation of enumKeys is as follows. SHIFT / LEFT_SHIFT are defined respectively, but unfortunately the behavior of the left Shift key will behave regardless of which one is sent.

Keys.java


public enum Keys implements CharSequence {
  ...
  SHIFT        ('\uE008'),
  LEFT_SHIFT   (Keys.SHIFT),
  CONTROL      ('\uE009'),
  LEFT_CONTROL (Keys.CONTROL),
  ALT          ('\uE00A'),
  LEFT_ALT     (Keys.ALT),
  LEFT         ('\uE012'),
  ARROW_LEFT   (Keys.LEFT),
  UP           ('\uE013'),
  ARROW_UP     (Keys.UP),
  RIGHT        ('\uE014'),
  ARROW_RIGHT  (Keys.RIGHT),
  DOWN         ('\uE015'),
  ARROW_DOWN   (Keys.DOWN),
  ...
}

solution

Keys implements CharSequence, and the constructor and toString () implementation are as follows.

Keys.java


public enum Keys implements CharSequence {
  ...

  private final char keyCode;
  private final int codePoint;

  Keys(Keys key) {
    this(key.charAt(0));
  }

  Keys(char keyCode) {
    this.keyCode = keyCode;
    this.codePoint = String.valueOf(keyCode).codePoints().findFirst().getAsInt();
  }

  ...

  @Override
  public String toString {
    return String.valueOf(keyCode);
  }
}

Also, WebElement.sendKeys only combines the given keycodes with line breaks and sends them to WebDriver. Therefore, it will be recognized normally by specifying it with a character string as shown below without using the KeyCode defined in Keys.SHIFT.

  WebElement element = webDriver.findElement(By.className("hoge"))
  element.sendKeys("ShiftRight");

Recommended Posts

Use Shift Right and Shift Left properly in Selenium
Use of Abstract Class and Interface properly in Java
Handling of date and time in Ruby. Use Date and Time properly.
Use selenium (Firefox) in Ruby in WSL environment
Difference between getText () and getAttribute () in Selenium
Use selenium (Chrome) in Ruby in WSL environment
Capture and save from selenium installation in Java
Use of Japanese fonts and external characters in JasperReport
Use different TransactionManager for metadata and step in spring-batch
Use variables for class and id names in haml