How to use executescript in Selenium WebDriver

There are so many instances when we have to use javascript to perform various tasks in test automation. In order to run JavaScript commands with Selenium, we can either use JavaScriptExecutor in Selenium or ExecuteScript. ExecuteScript is a part of Selenium WebDriver but its job is same as JavaScriptExecutor. 

Please see below some of the common examples of how to use ExecuteScript to run JavaScript commands.
WebElement searchbox = null;
searchbox = (WebElement)Driver.executeScript("return document.getElementById('gsc-i-id1');", searchbox);

How to use executeScript in selenium 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');"));

How to use executeScript for getting total no. of frames In browser

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

How to use executeScript for adding an Element in DOM

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

How to use executeScript for getting size of Window

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

How to use executeScript for navigating to a different page

Driver.executeScript("window.location = 'http://yahoo.com'");
Follow Us
Categories

Tags

APACHE code java jenkins selenium uft vbscript

Latest Posts
Want us to add
more code ?
5/5