121

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.

Cedric Druck
  • 1,032
  • 7
  • 20
JontyMC
  • 6,038
  • 6
  • 38
  • 39

9 Answers9

245

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.

ESV
  • 7,620
  • 4
  • 39
  • 29
JimEvans
  • 27,201
  • 7
  • 83
  • 108
  • 13
    NOTE the capitalisation in the word Java***S***cript. This caught me out. – WheretheresaWill Nov 12 '15 at 06:45
  • 3
    Jim's answer is about as authoritative as you can get. Check out the commit history on, well, every Selenium .NET file :-) – Ross Patterson May 18 '16 at 13:24
  • 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. – Almett Jun 23 '16 at 04:42
  • 1
    I find it awkward that I have to cast the driver. Why is `ExecuteJavascript` not just a method on the `driver`? – Kellen Stuart Jun 27 '19 at 18:05
  • 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. – JimEvans Jun 27 '19 at 19:12
56

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");
tanascius
  • 53,078
  • 22
  • 114
  • 136
Morten Christiansen
  • 19,002
  • 22
  • 69
  • 94
24

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()");
harishr
  • 17,807
  • 9
  • 78
  • 125
  • 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. – Jeffrey LeCours Oct 20 '17 at 15:41
  • what is the `Driver`? VS can't recognize that – anatol Sep 27 '18 at 05:01
14

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");
agentnega
  • 3,478
  • 1
  • 25
  • 31
8

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);
}
perryzheng
  • 199
  • 1
  • 8
  • 2
    Nice idea. For others reading this, your javascript code should return a DOM element. – joelsand Apr 12 '13 at 20:50
  • I didn't even consider this as possible. This is huge as I can now create a method using javascript to return nextSibling. – jibbs Jan 18 '17 at 18:25
1
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);

    }
1
public static class Webdriver
{        
    public static void ExecuteJavaScript(this IWebDriver driver, string scripts)
    {
        IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
        js.ExecuteScript(scripts);
    }

    public static T ExecuteJavaScript<T>(this IWebDriver driver, string scripts)
    {
        IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
        return (T)js.ExecuteScript(scripts);
    }
}

In your code you can then do:

IWebDriver driver = new WhateverDriver();
string test = driver.ExecuteJavaScript<string>(" return 'hello World'; ");
int test = driver.ExecuteJavaScript<int>(" return 3; ");
Gene Yuss
  • 33
  • 5
Mo D Genesis
  • 5,187
  • 1
  • 21
  • 32
1

Please use the below extension methods added to execute javascript and to take screenshot in Selenium.Support (.dll) of Selenium C#

https://www.nuget.org/packages/Selenium.Support/

IWebDriver driver = new ChromeDriver();
driver.Manage().Window.Maximize();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);
driver.Url = "https://phptravels.net/";

driver.ExecuteJavaScript("document.querySelector('#checkin').value='07-12-2022'");

driver.ExecuteJavaScript("document.querySelector('#checkout').value='17-12-2022'");

IWebElement ele1 = driver.FindElement(By.Id("checkin"));
driver.ExecuteJavaScript("arguments[0].value='07-12-2022'",ele1);

string output=driver.ExecuteJavaScript<string>("return 
document.querySelector('#checkin').value");
Console.WriteLine(output);

Screenshot sc= driver.TakeScreenshot();
sc.SaveAsFile("C:\\error.png");
0

The shortest code

ChromeDriver drv = new ChromeDriver();

drv.Navigate().GoToUrl("https://stackoverflow.com/questions/6229769/execute-javascript-using-selenium-webdriver-in-c-sharp");

drv.ExecuteScript("return alert(document.title);");


thammada.ts
  • 5,065
  • 2
  • 22
  • 33