How is this achieved? Here it says the java version is:
WebDriver driver; // Assigned elsewhere JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("return document.title");
But I can't find the C# code to do this.
How is this achieved? Here it says the java version is:
WebDriver driver; // Assigned elsewhere JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("return document.title");
But I can't find the C# code to do this.
The object, method, and property names in the .NET language bindings do not exactly correspond to those in the Java bindings. One of the principles of the project is that each language binding should "feel natural" to those comfortable coding in that language. In C#, the code you'd want for executing JavaScript is as follows
IWebDriver driver; // assume assigned elsewhere IJavaScriptExecutor js = (IJavaScriptExecutor)driver; string title = (string)js.ExecuteScript("return document.title");
Note that the complete documentation of the WebDriver API for .NET can be found at this link.
I prefer to use an extension method to get the scripts object:
public static IJavaScriptExecutor Scripts(this IWebDriver driver) { return (IJavaScriptExecutor)driver; }
Used as this:
driver.Scripts().ExecuteScript("some script");
How about a slightly simplified version of @Morten Christiansen's nice extension method idea:
public static object Execute(this IWebDriver driver, string script) { return ((IJavaScriptExecutor)driver).ExecuteScript(script); } // usage var title = (string)driver.Execute("return document.title");
or maybe the generic version:
public static T Execute(this IWebDriver driver, string script) { return (T)((IJavaScriptExecutor)driver).ExecuteScript(script); } // usage var title = driver.Execute("return document.title");
You could also do:
public static IWebElement FindElementByJs(this IWebDriver driver, string jsCommand) { return (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript(jsCommand); } public static IWebElement FindElementByJsWithWait(this IWebDriver driver, string jsCommand, int timeoutInSeconds) { if (timeoutInSeconds > 0) { var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds)); wait.Until(d => d.FindElementByJs(jsCommand)); } return driver.FindElementByJs(jsCommand); } public static IWebElement FindElementByJsWithWait(this IWebDriver driver, string jsCommand) { return FindElementByJsWithWait(driver, jsCommand, s_PageWaitSeconds); }
the nuget package Selenium.Support
already contains an extension method to help with this. Once it is included, one liner to executer script
Driver.ExecuteJavaScript("console.clear()");
or
string result = Driver.ExecuteJavaScript("console.clear()");
public void javascriptclick(String element) { WebElement webElement=driver.findElement(By.xpath(element)); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("arguments[0].click();",webElement); System.out.println("javascriptclick"+" "+ element); }