Monday, June 20, 2022

JavaScriptExecutor in Selenium WebDriver

 JavaScript:

  •  JavaScript is a programming language that interacts with HTML DOM within the browser.

JavaScriptExecutor:

  •  JavaScript executor is an interface provided by Selenium that gives a mechanism to execute JavaScript through Selenium WebDriver.
  •  It provides two methods such as “executeScript” & “executeAsyncScript” to run JavaScript on the currently selected frame, window, or page.

Uses of JavaScriptExecutor:

  •  There are locators in Selenium WebDriver like ID, Class, XPath, etc., to work with elements on a web page.
  •  Sometimes these default Selenium locators may not work.
  •  JavaScriptExecutor is used to perform operations on a web page.
  •  JavascriptExecutor in Selenium enables the WebDriver to interact with HTML DOM within the browser.


1. Type Text in a Text Box

 JavascriptExecutor js = (JavascriptExecutor) driver;

 js.executeScript("document.getElementById('Email').value='suriya@gmail.com';");


2. To Click on a Button

 js.executeScript("document.getElementById('enter your element id').click();");


3. To refresh browser window using Javascript

 js.executeScript("history.go(0)");


4. To get the inner text of the entire webpage in Selenium

 String Text =  js.executeScript("return document.documentElement.innerText;").toString();

 System.out.println(Text);


5. To get the Title of our webpage

 String Text =  js.executeScript("return document.title;").toString();

 System.out.println(Text);


6. To get the URL of a webpage

 String Text =  js.executeScript("return document.URL;").toString();

 System.out.println(Text);


7. To perform Scroll on an application

 js.executeScript("window.scrollBy(0,500)");

No comments:

Post a Comment