Search code examples
javaselenium-webdriverwebdriver

Paste a string into textbox using selenium java


String text = "test";

I want to paste the string text using selenium Keys.CONTROL+"v". But I just couldn't find the right way to do it. Can somebody helps me of any questions in stack overflow would be very helpful.

Just to be clear I don't want to copy a text from screen like this:

driver.findelement(by.xpath).sendKeys(Keys.CONTROL+"c") 

But I want to use directly the String text to paste it.

Thanks in advance


Solution

  • Updated as per requirement

    public static void main(String[] args) throws IOException, AWTException, InterruptedException {
    
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        ChromeDriver driver = new ChromeDriver(options);
        driver.get("https://www.google.com");
    
    
        WebElement we = driver.findElement(By.xpath("//textarea[@title='Search']"));
        String text = "test";
    
        StringSelection stringSelection = new StringSelection(text);
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(stringSelection, null);
        we.sendKeys(Keys.SHIFT, Keys.INSERT);
    
        Thread.sleep(50000);
        driver.close();
    }
    

    enter image description here