javascriptc#seleniumselenium-webdriverpage-title

How can we determine when to use JavaScriptExecutor in selenium c#?


TestInChrome1 throws me an exception - "OpenQA.Selenium.ElementNotInteractableException: element not interactable" However, when JavaScriptExecutor is used in TestInChrome2, it works well.

My questions are:

  1. why does Click() method is not working in TestInChrome1?

  2. how do can we determine that JavaScriptExecutor is necessary without trial and errors?

    [TestMethod]
    public void TestInChrome1()
    {
        IWebDriver driver = new ChromeDriver();
        driver.Navigate().GoToUrl("https://ultimateqa.com/");
        IWebElement element = driver.FindElement(By.TagName("title"));
        element.Click();
        driver.Quit();
    }
    
    
    
    
    [TestMethod]
    public void TestInChrome2()
    {
        IWebDriver driver = new ChromeDriver();
        driver.Navigate().GoToUrl("https://ultimateqa.com/");
        IWebElement element = driver.FindElement(By.TagName("title"));
        IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
        string title = (string)js.ExecuteScript("return document.title");
        driver.Quit();
    }
    

Solution

  • When we use selenium, it has methods written in such a way that it tries to emulate how user will interact with the webpage.

    So, lets take the case there is a button on the screen but it never displays on the visible area of the screen. Maybe it is not scrollable (or maybe it is always hidden) and will be never be available to user. Now this is a valid bug.

    In my case, I have encountered Element not interactable exception in mostly false positive (invalid, non-bug) scenarios

    If you see too many issues due to element not interactable , just catch this exception, take screenshot for your reference, generate a warning in logs for yourself and you can implement direct click using javascript executor in catch block. Atleast by generating warning for yourself, you can check if you are not missing out on an actual issue.

    Hope this helps.