November 24, 2019

Java script helpers for selenium actions

  November 24, 2019
We come across several scenarios where we cannot some actions on webelemets using selenium libraries only.

In such cases we have another option to use java script to these actions. We will be using the webdriver object along with the java script code to execute those on the web element.

One major scenario those who use selenium came across will be the highlight element option. In java we have default option to highlight element. But in C# we need to write a java script to do this.

Some other scenarios like scroll to element,click,Open a new tab in browser etc can also be done using java script.

        public static void HighlightElement(this IWebElement element,GenericBase objGen)
        {
          //  objGen.ScrollToElementLocation(element);

                var jsDriver = (IJavaScriptExecutor)objGen.driver;
                String highlightJavascript = @"arguments[0].style.cssText = ""border-width: 2px; border-style: solid; border-color: red"";";
                jsDriver.ExecuteScript(highlightJavascript, new object[] { element });

        }


        public static void JavaScriptClick(this IWebElement element,GenericBase objGen)
        {
            IJavaScriptExecutor executor = (IJavaScriptExecutor)objGen.driver;
            executor.ExecuteScript("arguments[0].click();", element);

        }


        public static void ScrollToElementLocation(this IWebElement element,GenericBase objGen)
        {           
            var script = "arguments[0].scrollIntoView(true);";
            IJavaScriptExecutor js = (IJavaScriptExecutor)objGen.driver;
            js.ExecuteScript(script, element);
        }

        /// <summary>
        /// Open a URL in new tab of same browser
        /// </summary>
        /// <param name="url"></param>
        public void OpenURLNewTab(string url)
        {
            IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;
            executor.ExecuteScript("window.open('" + url + "','_blank');");
            List<string> tabs = new List<string>(driver.WindowHandles);
            driver.SwitchTo().Window(tabs.ElementAt(1));

        }



        public void ScrollToBottom()
        {
            IJavaScriptExecutor js1 = (IJavaScriptExecutor)driver;
            js1.ExecuteScript("window.scrollBy(0,500)", "");
        }

        public void ScrollToTop()
        {
            IJavaScriptExecutor js1 = (IJavaScriptExecutor)driver;
            js1.ExecuteScript("scroll(0,0)");
            Thread.Sleep(3000);
        }
logoblog

Thanks for reading Java script helpers for selenium actions

Previous
« Prev Post

No comments:

Post a Comment

Bookmark this website for more workarounds and issue fixes.

Verify Zip file contents without extracting using C# + Selenium

While doing automation testing, we may get a scenario where we need to download a zip file and to validate the contents inside it. One way t...