Selenium JavaScript Usage | Selenium Automation Testing
Selenium Javascript Usage – Selenium Automation Testing
Selenium has a mature API that caters to the majority of automation tasks that you may want to throw at it. That being said, you will occasionally come across problems that the API doesn’t really seem to support. This was very much on the development team’s mind when Selenium was written. So, they provided a way for you to easily inject and execute arbitrary blocks of JavaScript. Let’s have a look at a basic example of using a JavaScript executor in Selenium:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("console.log('I logged something to the
Javascript console');");
Note that the first thing we do is cast a WebDriver object into a JavascriptExecutor object. The JavascriptExecutor interface is implemented through the RemoteWebDriver class. So, it’s not a part of the core set of API functions. Since we normally pass around a WebDriver object, the executeScript functions will not be available unless we perform this cast.
If you are directly using an instance of RemoteWebDriver or something that extends it (most driver implementations now do this), you will have direct access to the .executeScript() function. Here’s an example:
FirefoxDriver driver = new FirefoxDriver(new FirefoxProfile());
driver.executeScript("console.log('I logged something to the
Javascript console');");
The second line (in both the preceding examples) is just telling Selenium to execute an arbitrary piece of JavaScript. In this case, we are just going to print something to the JavaScript console in the browser.
Selenium RC launches the browser with itself as the proxy server (hence you may get certificate warning in some modes) and then it injects javascript – to play the test. This also means it can easily work in ALL browsers/platform – and it can be easily used to test AJAX(unlike professional tools).
Since Selenium is based on JavaScript, you can use it in your tests.It is an excellent way to extract information from the pages for later reuse.
There are 2 methods available:
getEval(script)
: it takes the script as a string, executes it and return the value to which the script evaluates too. In ruby useget_eval
orjs_eval
- Using this method, the
window
object refers to the Selenium context, which is different from the tested application’s JavaScript contextTo work around this, you need to get the application’swindow
object usingcurrentwindow = this.browserbot.getCurrentWindow()
* If you want to get an element, just useelement = this.browserbot.findElement("locator")
- Using this method, the
runScript(script)
: it actually adds a<script>
tag in the current page of the tested application, making it easier to debug
It involves the following topics
Free Selenium Practice Tests | Go To Selenium Practice Test Now
Apply for Selenium Certification Now!!
http://www.vskills.in/certification/Certified-Selenium-Professional