Lukas Bystricky
Lukas Bystricky

Reputation: 1272

Selenium paste text into textarea

Using Selenium, I'd like to edit the contents of a textarea. Calling textarea.SendKeys("My text") works, but it types it in letter by letter which is obviously quite slow for longer strings.

One workaround I found (http://code.google.com/p/selenium/issues/detail?id=2876) suggests that I copy the string to a clipboard and paste it into the textarea. The Keys reference they give is ambiguous between OpenQA.Selenium.Keys and System.Windows.Forms.Keys, so I tried both of them. Here's my code to do that:

Clipboard.SetDataObject("My  text");
textarea.SendKeys(OpenQA.Selenium.Keys.Control + "v");

This freezes the application. If I use System.Windows.Forms.Keys.Control instead, it types in controlv, which obviously is not what I want.

Does anyone have any idea as to what the problem might be?

Upvotes: 2

Views: 14304

Answers (2)

Atanas Atanasov
Atanas Atanasov

Reputation: 201

Hope this CopyPaste method helps:

using OpenQA.Selenium.Interactions;
     public void CopyPaste(string copy)
    {
        Clipboard.SetText(copy);
        new Actions(driver).SendKeys(OpenQA.Selenium.Keys.LeftShift + OpenQA.Selenium.Keys.Insert).Perform();
//because it switch to uppercase we do one more click
        new Actions(driver).SendKeys(OpenQA.Selenium.Keys.LeftShift).Perform();
    }

texarea.Click;
// if driver refuse to click textarea you can force it with:
//((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click();", driver.FindElement(By.XPath("//*[@id='MyTextareaId']")));
// not proven, but I think textarea.SendKeys(""); Will click inside the textarea


//Call the method
CopyPaste("Text Appear In the Textarea");

Upvotes: 1

StephenC
StephenC

Reputation: 159

I am able to use the same SendKeys when setting the clipboard to text:

Clipboard.SetText(trgt);
myTextArea.SendKeys(OpenQA.Selenium.Keys.Control + "v");

so perhaps the SetDataObject is an issue

Upvotes: 3

Related Questions