How to execute JavaScript in your C# tests

In WebDriver you can call javascript functions programatically without having to click on a link with javascript code as the href attribute. This functionality uses the IJavaScriptExecutor interface. This allows you to execute javascript commands on your browser from your Selenium Webdriver test. Here is a short example to get the current URL:

IWebDriver driver;
// ... ... ... 

IJavaScriptExecutor js = driver as IJavaScriptExecutor;
string url = (string)js.ExecuteScript("return document.url");

Or you can use functions or methods to be called also

IWebDriver driver;
// ... ... ... 

IJavaScriptExecutor js = driver as IJavaScriptExecutor;
js.ExecuteScript("OpenModalWindow('testfile.html')");

Leave a Comment