user6618310
user6618310

Reputation: 39

how to execute copy/paste using selenium webdriver

I want to execute a paste to a local variable already exist to an input text with selenium webdriver in java. for this I used this method:

public static void copyText(final String id, final String text) throws Exception {
        waitForJQueryProcessing(DRIVER, N_30);
        WebElement elem = DRIVER.findElement(By.id(id));
        DRIVER.findElement(By.id(id)).clear();
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Clipboard clipboard = toolkit.getSystemClipboard();
        StringSelection strSel = new StringSelection(text);
        clipboard.setContents(strSel, null);
        elem.sendKeys(Keys.chord(Keys.CONTROL, "v", text));
        System.out.println(text);

    }

When I execute the test, i will appear empty I don't know why ?

Upvotes: 1

Views: 19320

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193058

As you are trying to copy the character sequence from clipboard to a <input> element you can use the following solution:

//imports
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
//other lines of code
WebElement elem = DRIVER.findElement(By.id(id));
elem.clear();
String data = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
elem.sendKeys(data);

Upvotes: 1

Farheen Khanum
Farheen Khanum

Reputation: 50

Try the below code and check if it could help you.

String CopyText = driver.findElement(By.xpath("your xpath to order id")).getText();
driver.findElement (By.xpath("/html/body/main/div/div/div[2]/div/div/div[2]/div/table/tbody
/tr[2]/td[2]")).sendKeys(myOrderText ));

or try the below code:

// or any locator strategy that you find suitable 
        WebElement locOfOrder = driver.findElement(By.id("id of the element to be copied"));
Actions act = new Actions(driver);
act.moveToElement(locOfOrder).doubleClick().build().perform();
// catch here is double click on the text will by default select the text 
// now apply copy command 

driver.findElement(By.id("")).sendKeys(Keys.chord(Keys.CONTROL,"c"));

    // now apply the command to paste
    driver.findElement (By.xpath("/html/body/main/div/div/div[2]/div/div/div[2]/div/table/tbody/tr[2]/td[2]")).sendKeys(Keys.chord(Keys.CONTROL, "v"));

Upvotes: 1

Related Questions