0

I Want to past a text to a input field using CTRL + V in selenium Java. How to do it . Just I have a String So no need to copy a String from somewhere. I am trying to finding a way for it ?

Piyum Rangana
  • 71
  • 1
  • 9
  • 5
    Possible duplicate of [Performing a copy and paste with Selenium 2](https://stackoverflow.com/questions/11750447/performing-a-copy-and-paste-with-selenium-2) – Dushyant Tankariya Jun 07 '19 at 13:29
  • What is wrong with using a `.sendKeys()` to populate the input field with your String? Why do you need to perform a paste? – Ardesco Jun 07 '19 at 14:42
  • @Ardesco the only possible scenario I can think of in a testing environment where you'd want to -attempt- to paste is to test that an input element has been specifically designed to not allow that action, but I agree, and I doubt that's what this user is looking for. – Bill Hileman Jun 07 '19 at 14:49
  • I which case it won't work anyway so you will never know if you got the command right or not... ;) – Ardesco Jun 07 '19 at 15:06
  • You'd know if it worked correctly by testing it on a regular input field that does allow paste. Placing the logc in a try/catch and/or immediately inspecting the text value of the input after a paste would determine if the paste worked. – Bill Hileman Jun 07 '19 at 17:34
  • I know, I'm being facetious – Ardesco Jun 10 '19 at 07:38

2 Answers2

1

Assuming the string value is present in clipboard (using CTRL+C), you can retrive it as a string and pass on to your text field

  Toolkit toolkit = Toolkit.getDefaultToolkit();
            Clipboard clipboard = toolkit.getSystemClipboard();
            String copyFromClipboard= (String) clipboard.getData(DataFlavor.stringFlavor);
            System.out.println("String from Clipboard:" + result);
YourWebElement.sendkeys(copyFromClipboard);
Sureshmani Kalirajan
  • 1,938
  • 2
  • 9
  • 18
0

Actions Class : For handling keyboard and mouse events selenium provided Actions Class

keyDown(): This method simulates a keyboard action when a specific keyboard key needs to press.

keyUp(): The keyboard key which presses using the keyDown() method, doesn’t get released automatically, so keyUp() method is used to release the key explicitly.

sendKeys(): This method sends a series of keystrokes to a given web element.

    Actions action = new Actions(driver);
    action.keyDown(keys.CONTROL);    
    action.sendKeys("c");
    action.keyUp(keys.CONTROL);
    action.build().perform(); // copy is performed
    
    action = new Actions(driver);
    action.keyDown(keys.CONTROL);
    action.sendKeys("v");
    action.keyUp(keys.CONTROL);
    action.build().perform(); // paste is performed
AmitKS
  • 132
  • 4