0

I'm using Selenium Web Driver (Java, Chrome Browser). I would like to enter a tab character into a text area. By default, entering a tab character causes the next input to be focused, but I actually want the tab character to be printed into the textarea input.

Since my tests are running on a windows machine, I thought I could use the alt-code to enter the tab. IE

  1. Hold alt
  2. Press 0
  3. Press 9
  4. Release alt

But I'm not sure how to do this programmatically with WebDriver. I tried the following:

WebElement myTextArea = driver.findElement(By.cssSelector("form textarea"));

myTextArea.sendKeys("before_tab", Keys.chord(Keys.ALT, Keys.NUMPAD0, Keys.NUMPAD9), "after_tab");

...but it just printed "before_tabafter_tab" into the text area, I guess because it's pressing ALT, 0, and 9 all at the same time which doesn't translate to a printable character.

I would also consider pasting either via keyboard shortcut or context menu (this is actually closer to how I expect the user to enter text into the textarea), but I can't see how to put the text onto the clipboard for the selenium-driven browser to access.

Any help would be appreciated.

Saifur
  • 16,081
  • 6
  • 49
  • 73
Ryan Bennetts
  • 1,143
  • 2
  • 16
  • 29

3 Answers3

2

You can use following piece of Java code:

Robot rb = new Robot();

StringSelection textToPaste= new StringSelection("  ");//make sure u enter tab here

Toolkit.getDefaultToolkit().getSystemClipboard().setContents(textToPaste, null);

rb.keyPress(KeyEvent.VK_CONTROL);    
rb.keyPress(KeyEvent.VK_V);    
rb.keyRelease(KeyEvent.VK_V);    
rb.keyRelease(KeyEvent.VK_CONTROL);
Saifur
  • 16,081
  • 6
  • 49
  • 73
Shruti Singh
  • 180
  • 2
  • 11
  • Thanks. I didn't use the robot class, but your answer tells me how to put text onto the clipboard and that worked for me. – Ryan Bennetts Jun 02 '15 at 01:01
0

Have you tried using robot class

Focus on the text area

driver.findElement(By.cssSelector("form textarea")).sendKeys("");

Use robot class to enter keys into text area

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_0);
robot.keyPress(KeyEvent.VK_9);
robot.keyRelease(KeyEvent.VK_0);
robot.keyRelease(KeyEvent.VK_9);
robot.keyRelease(KeyEvent.VK_ALT);

Hope this helps you...

Saifur
  • 16,081
  • 6
  • 49
  • 73
Vicky
  • 2,999
  • 2
  • 21
  • 36
-1

You can use the windows Clipboard as follows:

 string text = "my text and tab" + Keys.Tab;
 Clipboard.SetText(text);

You can then use Keys.Control + "V" to paste this in your control.

Saifur
  • 16,081
  • 6
  • 49
  • 73
Steve
  • 367
  • 3
  • 11