You can execute required javascript call using WebDriver in your automation code using JavaScriptExecutor.
Example
WebDriver-JavaScriptExecutor
Logic
While returning values from the JavaScript code, need to use the return keyword. Based on the type of return value, need to type cast the executeScript() method.
Related Topics
Handling JavaScript Alerts
Taking Screenshots
Example
- you may want to fire an event on a particular element. (calling blur event directly)
- you may want to execute some script which will do some other operation. (instead of clicking directly call onclick targeted script)
- Cast the WebDriver instance to JavaScriptExecutor
- Execute the script using executeScript() method
Logic
WebDriver driver = new FirefoxDriver();
JavaScriptExecutor js=(JavaScriptExecutor)driver; //casting driver instance
String title=(String)js.executeScript("return document.title"); //for getting window tile
String name=(String)js.executeScript("return window.name"); //for getting window name
js.executeScript("$('#elementId').blur()"); //firing blur event on an element
executeScript() will return java.lang.Object, from that you can get your required data.
While returning values from the JavaScript code, need to use the return keyword. Based on the type of return value, need to type cast the executeScript() method.
- For decimal values, Double can be used,
- for non-decimal numeric values Long can be used,
- for Boolean values Boolean can be used.
- JavaScript code is returning an HTML element, then WebElement can be used.
- For text values, String can be used.
- If a list of objects is returned, then any of the values will work based on type of objects. Otherwise, a null will be returned.
Related Topics
Handling JavaScript Alerts
Taking Screenshots
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.