Execute JavaScript using Selenium WebDriver in C#
Asked Answered
W

9

122

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.

Weinstein answered 3/6, 2011 at 16:12 Comment(0)
W
247

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.

Winton answered 8/6, 2011 at 22:2 Comment(5)
NOTE the capitalisation in the word JavaScript. This caught me out.Hippocrene
Jim's answer is about as authoritative as you can get. Check out the commit history on, well, every Selenium .NET file :-)Ouabain
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.Nottingham
I find it awkward that I have to cast the driver. Why is ExecuteJavascript not just a method on the driver?Morbific
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.Winton
S
55

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");
Strontianite answered 26/8, 2011 at 11:3 Comment(1)
Selenium should have this by defaultMorbific
O
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()");
Olympias answered 14/4, 2017 at 3:57 Comment(2)
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.Leonhard
what is the Driver? VS can't recognize thatIsraelisraeli
W
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");
Willpower answered 15/6, 2012 at 6:3 Comment(1)
Can this be used to get WebElement and bool as well?Lucre
D
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);
}
Dessiedessma answered 3/7, 2012 at 23:11 Comment(2)
Nice idea. For others reading this, your javascript code should return a DOM element.Varuna
I didn't even consider this as possible. This is huge as I can now create a method using javascript to return nextSibling.Gaiseric
M
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);

    }
Mcbroom answered 14/2, 2017 at 11:34 Comment(0)
O
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; ");
Oldcastle answered 4/2, 2019 at 22:44 Comment(0)
M
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");
Matte answered 19/11, 2022 at 7:50 Comment(0)
P
0

The shortest code

ChromeDriver drv = new ChromeDriver();

drv.Navigate().GoToUrl("https://mcmap.net/q/180622/-execute-javascript-using-selenium-webdriver-in-c");

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


Propylene answered 1/6, 2020 at 19:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.