Search code examples
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.

    • If you use javascript executor, it will click on the buttob and your script won't be able to catch this issue
    • If you use selenium method for click, script will fail giving you some exception

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

    • if some field on screen was inactive earlier, you performed some action it became active. but due to faster execution, it was still inactive, when script interacted with it
    • Say you have dropdown on screen, you expand the dropdown and click on some field. Now you click some other field when dropdown was closed. While execution dropdown does not close immediately and element you want to access next is obsecured by that dropdown (can happen for popups, or some element that expands on screen, combobox, searchbox)

    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.