How to run JavaScript with Selenium WebDriver – 7 examples

In order to run JavaScript 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 showing how to use ExecuteScript to perform common tasks using JavaScript with Selenium.

Finding Element: Running javascript with Selenium executeScript

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

Changing style attribute of the Element

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

Getting Element attributes

This code snippet can be used to get element attributes running javascript.

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

Getting total no. of frames In browser

Using below code you can get total no of frames in a browser by running javascript using Selenium Executescript

driver.executeScript("document.frames.length;");

Adding an Element in DOM

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

Getting size of Window

This code can be used to get Window size by running javascript using Selenium Executescript

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

Navigating to a different page

This code can be used to navigate to a different page running javascript using Selenium Executescript

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

Discover more from Automation Script

Subscribe to get the latest posts sent to your email.

Related Posts