Categories

1 Answer

Aug 22, 2019
In general, we click on an element using click() method in Selenium.

For example:

driver.findElement(By.id("Id Value")).click();

1

driver.findElement(By.id("Id Value")).click();

Sometimes web controls don’t react well against selenium commands and we may face issues with the above statement (click()). To overcome such kind of situation, we use JavaScriptExecutor interface.

It provides a mechanism to execute Javascript through Selenium driver. It provides “executescript” & “executeAsyncScript” methods, to run JavaScript in the context of the currently selected frame or window.

There is no need to write a separate script to execute JavaScript within the browser using Selenium WebDriver script. Just we use predefined interface named ‘Java Script Executor’. We need to import the JavascriptExecutor package in the script.

Package:

import org.openqa.selenium.JavascriptExecutor;

1

import org.openqa.selenium.JavascriptExecutor;

Syntax:

JavascriptExecutor js = (JavascriptExecutor) driver;  

js.executeScript(Script,Arguments);

1

2

JavascriptExecutor js = (JavascriptExecutor) driver;  

js.executeScript(Script,Arguments);

Script – The JavaScript to execute

Arguments – The arguments to the script(Optional). May be empty.

Returns – One of Boolean, Long, String, List, WebElement, or null.

Let’s see some scenarios we could handle using this Interface:

1. To type Text in Selenium WebDriver without using sendKeys() method

2. To click a Button in Selenium WebDriver using JavaScript

3. To handle Checkbox

4. To generate Alert Pop window in selenium

5. To refresh browser window using Javascript

6. To get innertext of the entire webpage in Selenium

7. To get the Title of our webpage

8. To get the domain

9. To get the URL of a webpage

10. To perform Scroll on an application using  Selenium

11. To click on a SubMenu which is only visible on mouse hover on Menu

12. To navigate to different page using Javascript
Click here to read more about Selenium
Click here to read more about Insurance

Related questions

Madanswer
Aug 22, 2019 in Selenium
Aug 22, 2019 in Selenium
Aug 22, 2019 in Selenium
...