Execute JavaScript using Selenium WebDriver in C#

186,140

Solution 1

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.

Solution 2

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");

Solution 3

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<string>("console.clear()");

Solution 4

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<T>(this IWebDriver driver, string script)
{
    return (T)((IJavaScriptExecutor)driver).ExecuteScript(script);
}

// usage
var title = driver.Execute<string>("return document.title");

Solution 5

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);
}
Share:
186,140

Related videos on Youtube

JontyMC
Author by

JontyMC

Updated on July 08, 2022

Comments

  • JontyMC
    JontyMC almost 2 years

    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.

  • joelsand
    joelsand about 11 years
    Nice idea. For others reading this, your javascript code should return a DOM element.
  • rahoolm
    rahoolm about 9 years
    Can this be used to get WebElement and bool as well?
  • WheretheresaWill
    WheretheresaWill over 8 years
    NOTE the capitalisation in the word JavaScript. This caught me out.
  • Ross Patterson
    Ross Patterson almost 8 years
    Jim's answer is about as authoritative as you can get. Check out the commit history on, well, every Selenium .NET file :-)
  • Almett
    Almett almost 8 years
    Could you please tell me how to click a button in C#? Answers like arguments[0].click(); is not working for me? I have no exception when i execute my code, but it doesn't click the button.
  • jibbs
    jibbs over 7 years
    I didn't even consider this as possible. This is huge as I can now create a method using javascript to return nextSibling.
  • Jeffrey LeCours
    Jeffrey LeCours over 6 years
    This is a nice, modern solution. The extension method adds validation that the driver implements IJavaScriptExecutor and gives a better exception message if the return type is null when it shouldn't be or can't be cast to the desired return type.
  • anatol
    anatol over 5 years
    what is the Driver? VS can't recognize that
  • Kellen Stuart
    Kellen Stuart almost 5 years
    I find it awkward that I have to cast the driver. Why is ExecuteJavascript not just a method on the driver?
  • Kellen Stuart
    Kellen Stuart almost 5 years
    Selenium should have this by default
  • JimEvans
    JimEvans almost 5 years
    That's a leftover from a time when not every driver implementation supported executing arbitrary JavaScript. The .NET bindings, like the Java ones use role-based interfaces to model functionality that may be supported by one driver, but not all. In the Support assembly (WebDriver.Support.dll, available via NuGet in the Selenium.Support package), there's an extension method that handles the casting for you and makes it look like the driver has an ExecuteJavaScript method.