Wednesday, February 13, 2013

How to execute JavaScript using Selenium WebDriver

With Java Script we can access the DOM Properties. By doing so we can get the properties values of those objects.

Say i have a Div or a Span control like below:
<Div id="SampleDiv1">I am in Div</Div> or
<Span id="SampleSpan1">I am in Span</Div>

Here we have two solutions to get the value of the objects.

Solution 1: Use the getAttribute method.
This method is described in below location:

So for ex above, we can use like:
String sReturnText=driver.findElement("SampleSpan1")).getAttribute("innerHTML");

Because in the above example we are trying to get text from the control we can directly use getText method like below:
String sReturnText=driver.findElement("SampleSpan1")).getText();

Solution 2: We can get the DOM properties be JavaScript
There might be situations you will be needing to run the JavaScript in your automation. To do this/cover the example follow below steps:
String sJScript = "return document.getElementById('SampleSpan1').innerHTML;";
String sReturnText = (String) ((JavascriptExecutor) driver).executeScript(sJScript);

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.