What is JavaScriptExecutor in selenium?

What is JavaScript and why we use it in selenium?
Java script is an object-oriented programming language commonly used to create interactive effects within web browsers. It is used by Selenium webdriver to perform some actions. We use Java in our test case and we implemented almost all feature but some features we can’t handle using Java so we need scripting.

What is JavaScriptExecutor?
JavaScriptExecutor is an interface which provides mechanism to execute Javascript through selenium driver. 

Package to import:
import org.openqa.selenium.JavascriptExecutor;

Syntax:
JavascriptExecutor js = (JavascriptExecutor) driver;  
js.executeScript(ScriptToExecute,OptionalArguments);
JavaScriptExecutor

Example Code:
Example 1: How to generate Alert Pop window in selenium?
1
2
JavascriptExecutor js = (JavascriptExecutor)driver;
Js.executeScript("alert('hello world!');");

Example 2: How to click a button in Selenium WebDriver using JavaScript?
1
2
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", element);

Example 3: How to refresh browser window using Javascript ?
1
2
JavascriptExecutor js = (JavascriptExecutor)driver;
driver.executeScript("history.go(0)");

Example 4: How to get innertext of the entire webpage in Selenium?

1
2
JavascriptExecutor js = (JavascriptExecutor)driver;
string sText =  js.executeScript("return document.documentElement.innerText;").toString();

Example 5: How to get the Title of our webpage?
1
2
JavascriptExecutor js = (JavascriptExecutor)driver;
string sText =  js.executeScript("return document.title;").toString();

Example 6:How to perform Scroll on application using  Selenium?
1
2
3
 JavascriptExecutor js = (JavascriptExecutor)driver;
//Vertical scroll - down by 50  pixels
js.executeScript("window.scrollBy(0,50)");

Example 7: How to navigate to different page using Javascript?
1
2
3
JavascriptExecutor js = (JavascriptExecutor)driver;
//Navigate to new Page
js.executeScript("window.location = 'https://www.facebook.com/uftHelp'");



<-- Previous || Next -->

2 comments:

  1. Is it like hacking through script?

    ReplyDelete
  2. You are doing a good job and sharing your knowledge to others! it was one of the good post to read and useful to improve the knowledge as updated one, keep doing the good work.

    Selenium Training in Electronic City, Bangalore my knowledge as updated one, keep blogging.

    ReplyDelete