Search code examples
c#seleniumfirefoxgeckodriver

SendKeys lasting too long (C# Selenium geckodriver)


I'm trying to send keys (a string of 1000 lines) to a textarea using Selenium for Firefox in C#, but Selenium freezes for a minute, and after that, an error appears but the text appears written on the textarea.

This is the error:

The HTTP request to the remote WebDriver server for URL timed out after 60 seconds

What can it be?

Thank you,


Edit

String text;
IWebElement textarea;

try
{
    textarea.Clear();
    textarea.SendKeys(text); //Here's where it freezes for 60 seconds.
}
catch(Exception e)
{
    //After those 60 seconds, the aforementioned error appears.
}

//And finally, after another 30 seconds, the text appears written on the textarea.

text and textarea represent some real values, which are correct (the element is present, etc)


Solution

  • The exception occurs because the driver doesn't respond within 60 seconds, probably because SendKeys is taking more than 60 seconds to simulate all keys.

    Either split your text into smaller strings and call SendKeys for each one of them:

    static IEnumerable<string> ToChunks(string text, int chunkLength) {
        for (int i = 0; i < chunkLength; i += chunkLength)
            yield return text.Substring(i, Math.Min(chunkLength, text.Length - i));
    }
    
    
    foreach (string chunk in ToChunks(text, 256))
        textarea.SendKeys(chunk);
    

    Or simulate a text insertion from a user (paste from clipboard or drop). This use case is not directly supported by Selenium, so you'll have to use a script injection:

    string JS_INSERT_TEXT = @"
        var text = arguments[0];
        var target = window.document.activeElement;
    
        if (!target || target.tagName !== 'INPUT' && target.tagName !== 'TEXTAREA')
          throw new Error('Expected an <input> or <textarea> as active element');
    
        window.document.execCommand('inserttext', false, text);
        ";
    
    textarea.Clear();
    ((IJavaScriptExecutor)driver).ExecuteScript(JS_INSERT_TEXT, text);