How to execute JavaScript in Selenium

Java

In Java, the Webdriver can be cast to a JavaScriptExecutor, which has an executeScript() method, which returns an Object.

String title = ((JavascriptExecutor) driver).executeScript("return document.title;").toString();

Python

In Python, the Webdriver has an execute_script() method.

title = driver.execute_script("return document.title;")

C#

In C#, the Webdriver can be cast to an IJavaScriptExecutor, which has an ExecuteScript() method, which returns an Object.

String title = ((IJavaScriptExecutor) driver).ExecuteScript("return document.title;").ToString();