Thursday, April 13, 2017

Execute JavaScript based code using Selenium Webdriver

We can use the Selenium WebDriver API to design and execute javascript code on the browser session. 

To execute JavaScript code, we will use the " IJavaScriptExecutor" interface that provides us the capability to execute the code and control it on a given browser session.
תוצאת תמונה עבור ‪selenium webdriver  javascript‬‏

Knowing the important keys!

1.     Prior to using the IJavaScriptExecutor interface, we first need to cast the WebDriver instance to an IJavaScriptExecutor instance.

IWebDriver Firefox = new FirefoxDriver();
IJavaScriptExecutor Execution = (IJavaScriptExecutor)Firefox;

2.     The JS code execution is performed with the ".executeScript()".
3.     When using the above method, we will need to use the "return" keyword and cast the returned valued from the script execution into the relevant type (int, string etc.).

String returnedJSvalue = (string) Execution".executeScript("code that return string")".
public void RunningJavaScript(){
//Phase 1: Casting the WebDriver instance to a IJavaScriptExecutor interface

//Phase 2: Creating a new Driver instance
IWebDriver Firefox = new FirefoxDriver();

//Phase 3: Navigate to a web location

//Phase 4: Casting the WebDriver instance to a IJavaScriptExecutor interface
IJavaScriptExecutor JsExecution = (IJavaScriptExecutor)Firefox;

//Phase 5: Using the JsExecution.ExecuteScript() to execute the JS code
string URLName = (string)JsExecution.ExecuteScript("return document.URL");

//Phase 6: Validation
Assert.AreEqual("", URLName);

No comments:

Post a Comment

My Presentations