0

Since updating to Selenium 4.1.2, my tests fail when selecting a value from dropdown using all options: by value, index and visible text. See error below:

"JavaScriptException: Cannot click on option element. Executing Javascript click function returned an unexpected error, but no error could be returned from Internet Explorer's JavaScript engine."

Any workarounds?

Glenn P
  • 37
  • 8

1 Answers1

0

It seems to be a recurring error in various versions of the driver. However, you could work around the dropdownlist management issue by defining a method that defines Js code. This example shows C# code, but the principle is the same if you use other languages

public void SelectOption(By by, String value) 
        {
            Actions actions = new Actions(Driver);
            IWebElement wele = Driver.FindElement(by);
            IJavaScriptExecutor jsExecutor = (IJavaScriptExecutor)Driver;
            jsExecutor.ExecuteScript("arguments[0].click();", wele);
            jsExecutor.ExecuteScript("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text.toUpperCase() == arguments[1]){ select.options[i].selected = true; } }", wele, value);
            Thread.Sleep(TimeSpan.FromSeconds(1));                 
        }

If on the dropdownlists are functions of the type onclick="" or onchage= "" remember to define them on the js code.
As in the following example, select.onchange() is defined.

 public bool SelectOptionOnChange(By by, String value)
    {
        bool failed = true;
        Actions action = new Actions(Driver);
        if (!m_sHelper.boolWaitForElementIsDisplayed(by, TimeToWait.med))
            m_sHelper.SetErrorMsg("Elemento dropdownlist non identificato: " + value);
        else
        {
            IWebElement dropElement = Driver.FindElement(by);
            SelectElement dropOptions = new SelectElement(dropElement);
           
            if (dropOptions.Options.Count == 0)
                return true;
           
            try
            {
                IJavaScriptExecutor jsExecutor = (IJavaScriptExecutor)Driver;
                jsExecutor.ExecuteScript("arguments[0].click();", dropElement);
                jsExecutor.ExecuteScript("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text.toUpperCase() == arguments[1]){ select.options[i].selected = true; select.onchange();} }", dropElement, value);
                Thread.Sleep(TimeSpan.FromSeconds(1));                   
                failed = false;
            } catch (Exception)
            {
                failed = true;
            }
        }
        return failed;
    }