Forceful Click using JavaScript
In the cases, where above stated approaches don’t work, we need to forcefully click on an element using Javascript. This can be done using executeScript and click functions of JavascriptExecutor. In this approach, we will see how we can forcefully click an element using JavascriptExecutor.
1. executeScript: The feature of JavascriptExecutor that enables to execution of JavaScript code within the context of the current browser window is known as executeScript.
2. click(): The function that is used to simulate a mouse click action on a web element is known as the click function.
Syntax:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(“arguments[0].click();”, element);
Here,
element: It is the element that is out of the viewport and you want to click forcefully.
Example:
In this example, we opened the Geeks For Geeks website (link) and then found the element containing the text ‘Problem of the day’ which is out of the viewport, and then clicked on that element using JavascriptExecutor.
Java
//Importing the Selenium libraries import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.By; public class selenium3 { public static void main(String[] args) { // Specify the location of the driver System.setProperty( "webdriver.chrome.driver" , "C:\\Users\\Vinayak Rai\\Downloads\\chromedriver-win64\\chromedriver-win64\\chromedriver.exe" ); // Initialising the driver WebDriver driver = new ChromeDriver(); // Launch the website // Maximize the screen driver.manage().window().maximize(); // Stating the Javascript Executor driver JavascriptExecutor js = (JavascriptExecutor) driver; // Find Problem of the day text WebElement element = driver.findElement(By.xpath( "// *[contains(text(),'Problem of the day')]" )); // Forcefully click on an element js.executeScript( "arguments[0].click();" , element); } } |
Output:
How to Force Selenium WebDriver to Click on Element which is Not Currently Visible?
A programming language that is used to execute a set of instructions that a computer can understand and execute to perform various tasks is known as Java. Java can be controlled autonomously using various automation tools.
Table of Content
- Visibility criteria
- Wait for Visibility
- Scroll the Element into View
- Address Underlying Issues
- Forceful Click using JavaScript
- Conclusion
- FAQs
Selenium is one such tool, that can make the work of developer and tester easier. There are various instances when the user needs to click or perform a certain action on the element that is currently not in the scope of visibility. In this article, we will see how we can forcefully click on an element that is not currently visible using Selenium webdriver.