I needed to get the return value of a JavaScript function executed through WebDriver. Specifically, I needed to get the text from a WYSIWYG editor called TinyMCE. Here was my solution. Example:
String javascript = " ( function getText() { " +
" for(i=0; i < window.frames.length; i++) { " +
" if( window.frames[i].document.getElementById('tinymce') != null ) { " +
" return window.frames[i].document.getElementById('tinymce').innerHTML; " +
" } } } )() ";
Here is my runScript method:
public String runScript(String javasript){
JavascriptExecutor js = (JavascriptExecutor) driver;
return (String) js.executeScript("return " + javascript);
}
This is the basic syntax:
( function x() { //do something & return value } )()
To Use with an argument:
( function(x) { //do something & return value } )(arg);