ExecuteScript in Selenium WebDriver – 7 use cases with Java

In order to run JavaScript commands with Selenium WebDriver, we can either use JavaScriptExecutor or ExecuteScript in Selenium. ExecuteScript is a part of Selenium WebDriver but its job is same as JavaScriptExecutor. 

This can be used for many tasks and it is extremely useful. Let’s see some of the common examples of how to use ExecuteScript to run common JavaScript commands in Selenium.

How to use executeScript for finding Element

WebElement searchbox = null;
searchbox = (WebElement)driver.executeScript("return document.getElementById('gsc-i-id1');", searchbox);

How to use executeScript for changing style attribute of the Element

driver.executeScript("document.getElementById('text-4').style.borderColor = 'Red'");

How to use executeScript in selenium for getting Element attributes

String className = driver.executeScript("return document.getElementById('gsc-i-id1').getAttribute('class');"));

Using executeScript for getting total no. of frames In browser


Using executeScript for adding an Element in DOM

driver.executeScript("var btn=document.createElement('BUTTON');"+"document.body.appendChild(btn);");

Using executeScript for getting size of Window

driver.executeScript("return window.innerHeight;")
driver.executeScript("return window.innerWidth;")

Using executeScript for navigating to a different page

driver.executeScript("window.location = 'http://yahoo.com'");

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.