This was my answer to a question on Quora
in Java (and similarly in C#):
Object executeScript(String script, Object... args)
Object executeAsyncScript(String script, Object... args)
WebElement it will apply the script to the corresponding HTML element. Arguments are added to the JS magic
arguments variable which represents the values passed to a function. If the code executed returns a value, that is returned to your Selenium code
Each driver is responsible for implementing it for the browser.
RemoteWebDriver implements it as well.
in this case, you cast your driver instance (which really does implement
WebDriver driver = new ChromeDriver();
// base type ‘WebDriver’ does not define executeScript() although our instance that extends RemoteWebDriver actually does implement it.
js.executeScript(“alert(‘hi from Selenium’);”
RemoteWebDriver driver = new RemoteWebDriver(url, capabilities);
// information about our type is not lost so the Java compiler knows our object implements executeScript()
WebElement element = driver.findElement(By.id(“mybutton”));
String htmlsnippet = driver.executeScript(“return document.querySelector(‘#myid’).outerHTML” , element);
Why would you do this?