Tuesday, July 25, 2017

Why JavaScript is used in Selenium and What is JavaScriptExecutor?

Why JavaScript is used in Selenium?
Sometimes native actions like clicking, text entering will not work on the browsers, and we can’t access the hidden elements with our scripts in Java or Python or some other language. In such situations with the help of running JavaScript in browser we can make it work out (most of the times). Selenium Webdriver provided JavaScriptExecutor to run the JavaScripts.
Example, the native clicks in the IE browser will not have any effect, it clicks the button or link but there will be no response from it. But when I used JavaScript here to click the element it worked like a gem. Another situation is not able to enter text using sendKeys, using JavaScript I was able to enter the text in the field. Hope this gives basic understanding for using JavaScript in Selenium. 
JavaScriptExecutor:
  • JavaScriptExecutor is an Interface provided by Selenium WebDriver. WebDriver uses the JavaScriptExecutor to run the JavaScripts.
  • JavaScript is used along with HTML to enhance the browser capabilities like Dynamic pages creation, Dynamic validation of fields, To communicate with HTML DOM and etc.
  • When JavaScript is executed using JavaScriptExecutor, it communicates with the browser's DOM and performs necessary action.
  • JavaScriptExecutor provides two methods to execute JavaScript executeScript() and executeAsyncScript().
  • This is available under the package org.openqa.selenium.JavaScriptExecutor;

Syntax:
script- The JavaScript that needs be executed. arguments- aruguments to the script. It is optional field.
Below are the some of the examples using JavaScriptExecutors:
1) How to click an element using JavaScriptExecutor?
2) How to refresh the browser?
3)How to enter text using JavaScriptExecutor?
4)How to scroll page to the bottom with JavaScriptExecutor?
5) How to check a checkbox using JavaScriptExecutor? These are the few examples. That's all about the JavaScript and JavaScriptExecutor.

No comments:

Post a Comment

DevOps 01: What is DevOps and How it benefits organizations?

DevOps is a culture in an organization, where the development team and operations team help each other by sharing information, process and t...